javascript Jquery ajax 调用超时。
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12411161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery ajax call timeout.
提问by RaviTeja
I've an ajax call to set of urls to get html content. But some of the urls are taking long time to get the content, i'm okay to skip those which take more than say 1 sec.
我有一个 ajax 调用来获取 html 内容。但是有些网址需要很长时间才能获取内容,我可以跳过那些需要超过 1 秒的网址。
for (url in list) {
$.ajax({
'url': url,
type: 'get',
timeout: 1000,
success: function () {
//doSomething
},
complete: function () {
//what to write?
}
});
}
Can you help me in how to abort the ajax call if it timeouts and execute the complete function.
如果超时并执行完整的函数,你能帮助我如何中止 ajax 调用吗?
Lemme know if i'm not clear. Thanks
如果我不清楚,让我知道。谢谢
回答by Dylan
First, change $.ajax(function() {
to $.ajax({
, because the argument you are trying to use is an object, not a function.
首先,更改$.ajax(function() {
为$.ajax({
,因为您尝试使用的参数是一个对象,而不是一个函数。
Since you specify a timeout in your options object, if the page doesn't respond in time, the ajax method will tell your error
function so, as long as you specify one.
由于您在选项对象中指定了超时,如果页面没有及时响应,ajax 方法会告诉您的error
函数,只要您指定一个。
$.ajax({
'url': yourUrlHere,
success: function(){ /*do stuff*/ },
timeout: 1000,
error: function(xhr, status, err){
//status === 'timeout' if it took too long.
//handle that however you want.
console.log(status,err);
}
});
See the documentation for $.ajax
here, as it has a pretty good explanation of the function.
回答by Sushanth --
You can abort the Request if that happens and go on to the next one..
如果发生这种情况,您可以中止请求并继续下一个请求。
var ajaxRequests = null;
for(url in list){
var newRequest = $.ajax({
type: 'GET',
url: url,
data: '{}',
dataType: 'json',
beforeSend: function() {
var r = ajaxRequest;
if (r != null && r != undefined) {
r.abort();
}
},
success: function(result) {
// what has to be done if the ajax request comes through
},
complete: function() {
ajaxRequests = null;
}
ajaxReqs = newRequest;
}