jQuery:处理失败的AJAX请求的后备 [英] jQuery: Handle fallback for failed AJAX Request
问题描述
jQuery能否为失败的AJAX调用提供后备?这是我的尝试:
Can jQuery provide a fallback for failed AJAX calls? This is my try:
function update() {
var requestOK = false;
$.getJSON(url, function(){
alert('request successful');
requestOK = true;
});
if (!requestOK) {
alert('request failed');
}
}
。 getJSON()方法被调用,我获得消息请求失败,在回调函数之前有机会设置requestOK变量。我认为这是因为代码并行运行。有办法处理这种情况吗?我想到了链接或某种方式等待AJAX请求,包括它的回调函数。但是怎么样?
Unfortunately, even if the callback function of the $.getJSON() method is called, i get the message 'request failed', before the callback function has the opportunity to set the requestOK variable. I think it's because the code runs in parallel. Is there a way to handle such situations? I thought about chaining or some way of waiting for the AJAX request, including its callback function. But how? Does anyone know how to do that?
推荐答案
您需要使用底层 $。ajax 调用,或 ajaxError function。这里是$ .ajax方法:
You will need to either use the lower level $.ajax call, or the ajaxError function. Here it is with the $.ajax method:
function update() {
$.ajax({
type: 'GET',
dataType: 'json',
url: url,
timeout: 5000,
success: function(data, textStatus ){
alert('request successful');
},
error: function(xhr, textStatus, errorThrown){
alert('request failed');
}
});
}
EDIT > timeout 到 $。ajax
调用并将其设置为五秒。
EDIT I added a timeout
to the $.ajax
call and set it to five seconds.
这篇关于jQuery:处理失败的AJAX请求的后备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!