【发布时间】:2020-12-10 05:04:24
【问题描述】:
我正在使用 fetch 获取 json 数据并使用结果呈现列表项。包含fetch 的函数由按钮触发。但是,如果我在初始 fetch 仍在运行时单击它,来自它的数据将在我的新呼叫之上加载。
我已使用window.stop() 来阻止此行为,但有更好的解决方案吗?
function updateTable() {
fetch('/json')
.then((response) => {return response.json()})
.then((response) => {
response.records.forEach(el => {
return '<li>' + el.Name + '</li>';
})
})
}
$('button').click(function(){
window.stop();
$('body').empty();
updateTable()
})
已编辑答案:在重新阅读链接线程时,使用fetch 使用新的signal 属性,我更新了我的代码以使用新的AbortController。记录here 的诀窍是在再次调用该函数时重新定义控制器。与window.stop() 相比的优势在于,停止只会影响fetch。
var controller = "";
var signal = "";
function updateTable() {
controller = new AbortController();
signal = controller.signal;
fetch('/json', {signal})
.then((response) => {return response.json()})
.then((response) => {
response.records.forEach(el => {
return '<li>' + el.Name + '</li>';
})
})
}
$('button').click(function(){
controller.abort();
$('body').empty();
updateTable()
})
【问题讨论】:
-
在加载时禁用该按钮,或在您单击该按钮时取消挂起的 Web 请求。
-
不应将答案编辑到问题中。相反,将正确答案标记为“已接受”。如果您自己找到解决方案,请写下您自己的答案,并将其标记为已接受。
-
抱歉,我无法添加新答案(问题已被阻止)。为什么还要做这一切?我相信它会帮助其他人。
标签: javascript jquery fetch