gpt4 book ai didi

javascript - 如果SPA(单页应用程序)中的其他页面加载中断,如何避免先前的ajax响应?

转载 作者:行者123 更新时间:2023-12-02 22:45:40 26 4
gpt4 key购买 nike

请问一些关于SPA的概念吗?我使用 SPA 开发了客户端网页。在菜单 A 中单击它请求一些 ajax 调用并等待响应。在此期间,如果我转到另一个页面 B,A 的 ajax 响应就会到来,它会尝试调用已经加载的 javascript 代码,因为浏览器不会在 SPA 中执行刷新。如何避免这种情况,忽略之前A的所有ajax响应?

$.ajax({
url: url,
type: "GET",
dataType: "json",
headers: {"Authorization": 'Token ' + myToken},
success: function(response) {
my_callback(response); // <== I want to block this if leaves current page...
},
error: function(response) {
},
complete: function(response) {
}
});

最佳答案

您可以abort的请求。

The XMLHttpRequest.abort() method aborts the request if it has already been sent. When a request is aborted, its readyState is changed to XMLHttpRequest.UNSENT (0) and the request's status code is set to 0.

    var xhr = $.ajax({
url: url,
type: "GET",
dataType: "json",
headers: { "Authorization": 'Token ' + myToken },
success: function (response) {
my_callback(response); // <== I want to block this if leaves current page...
},
error: function (response) {
},
complete: function (response) {
}
});

if(pageNavigates){
xhr.abort();
}

关于javascript - 如果SPA(单页应用程序)中的其他页面加载中断,如何避免先前的ajax响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58411719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com