Spaces:
Sleeping
Sleeping
Update static/script.js
Browse files- static/script.js +22 -9
static/script.js
CHANGED
|
@@ -1,21 +1,34 @@
|
|
|
|
|
| 1 |
const textGenForm = document.querySelector('.text-gen-form');
|
| 2 |
|
|
|
|
| 3 |
const translateText = async (text) => {
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
| 5 |
const inferJson = await inferResponse.json();
|
| 6 |
|
|
|
|
| 7 |
return inferJson.output;
|
| 8 |
};
|
| 9 |
|
|
|
|
| 10 |
textGenForm.addEventListener('submit', async (event) => {
|
| 11 |
-
|
|
|
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
| 21 |
});
|
|
|
|
| 1 |
+
// 从文档中选择具有类名 'text-gen-form' 的表单元素
|
| 2 |
const textGenForm = document.querySelector('.text-gen-form');
|
| 3 |
|
| 4 |
+
// 定义一个异步函数,用于翻译(或生成)文本
|
| 5 |
const translateText = async (text) => {
|
| 6 |
+
// 发送一个 GET 请求到 /infer_t5 路由,携带输入文本作为查询参数
|
| 7 |
+
const inferResponse = await fetch(`infer_t5?input=${encodeURIComponent(text)}`);
|
| 8 |
+
|
| 9 |
+
// 等待响应并将其解析为 JSON 格式
|
| 10 |
const inferJson = await inferResponse.json();
|
| 11 |
|
| 12 |
+
// 返回生成的文本
|
| 13 |
return inferJson.output;
|
| 14 |
};
|
| 15 |
|
| 16 |
+
// 为表单添加提交事件监听器
|
| 17 |
textGenForm.addEventListener('submit', async (event) => {
|
| 18 |
+
// 阻止表单的默认提交行为(例如页面刷新)
|
| 19 |
+
event.preventDefault();
|
| 20 |
|
| 21 |
+
// 获取输入框元素,通过 ID 'text-gen-input'
|
| 22 |
+
const textGenInput = document.getElementById('text-gen-input');
|
| 23 |
+
|
| 24 |
+
// 选择用于显示输出的段落元素,具有类名 'text-gen-output'
|
| 25 |
+
const textGenParagraph = document.querySelector('.text-gen-output');
|
| 26 |
|
| 27 |
+
try {
|
| 28 |
+
// 调用 translateText 函数并等待其返回结果,然后设置到段落的文本内容中
|
| 29 |
+
textGenParagraph.textContent = await translateText(textGenInput.value);
|
| 30 |
+
} catch (err) {
|
| 31 |
+
// 如果发生错误,打印错误信息到控制台
|
| 32 |
+
console.error(err);
|
| 33 |
+
}
|
| 34 |
});
|