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