gpt4 book ai didi

jQuery:处理失败的 AJAX 请求的回退

转载 作者:IT老高 更新时间:2023-10-28 12:47:39 30 4
gpt4 key购买 nike

jQuery 能否为失败的 AJAX 调用提供回退?这是我的尝试:

function update() {
var requestOK = false;

$.getJSON(url, function(){
alert('request successful');
requestOK = true;
});

if (!requestOK) {
alert('request failed');
}
}

不幸的是,即使调用了 $.getJSON() 方法的回调函数,我还是在回调函数有机会设置 requestOK 变量之前收到消息“请求失败”。我认为这是因为代码并行运行。有没有办法处理这种情况?我考虑过链接或等待 AJAX 请求的某种方式,包括它的回调函数。但是怎么做?有人知道怎么做吗?

最佳答案

您将需要使用较低级别的 $.ajax调用,或ajaxError功能。这里是 $.ajax 方法:

function update() {
$.ajax({
type: 'GET',
dataType: 'json',
url: url,
timeout: 5000,
success: function(data, textStatus ){
alert('request successful');
},
fail: function(xhr, textStatus, errorThrown){
alert('request failed');
}
});
}

EDIT我在 $.ajax 调用中添加了一个 timeout 并将其设置为 5 秒。

关于jQuery:处理失败的 AJAX 请求的回退,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1844370/

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