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变量。我认为这是因为code并行运行。有没有一种方法来处理这种情况?我想到了链接或等待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?
推荐答案
您需要可以使用较低的水平 $就打电话,或 ajaxError 的功能。在这里,它与$阿贾克斯方式:
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');
}
});
}
修改我添加了一个暂停
到 $。阿贾克斯
通话,并将其设置为5秒。
EDIT I added a timeout
to the $.ajax
call and set it to five seconds.
这篇关于jQuery的:处理回退失败的AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!