javascript 如何使用jQuery检查ajax调用是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13087421/
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
How to check if ajax call exists using jQuery?
提问by Lucas
I know my title isn't very clear.
我知道我的标题不是很清楚。
For example, this is the structure of my code:
例如,这是我的代码结构:
if (foo == something) {
// Ajax call 1, let it be $.ajax("foo1.html") and so on
} else {
// Ajax call 2, let it be $.ajax("foo2.html") and so on
}
How would I test if $.ajax("foo1.html")
has actually been run?
我将如何测试是否$.ajax("foo1.html")
已实际运行?
Please don't tell me to test if foo == something
again. My actual code is much, much more complicated, so please answer the question from the view of the ajax call.
请不要告诉我foo == something
再次测试。我的实际代码要复杂得多,所以请从 ajax 调用的角度回答问题。
Is this possible at all?
这可能吗?
回答by jAndy
I'm not sure if I understood you right, but jQuery will mix a Deferredobject into its jXHRobject and you can just check its state.
我不确定我的理解是否正确,但是 jQuery 会将Deferred对象混合到它的jXHR对象中,你可以检查它的状态。
var resp = $.ajax({});
// somewhere else...
if( resp.state() === 'resolved' ) {
}
Other states are rejected
and pending
, see http://api.jquery.com/deferred.state/
其他状态是rejected
and pending
,参见http://api.jquery.com/deferred.state/
Of course, you can get all advantages of those Deferredobjects aswell, like adding more event handlersfor certain things afterwards (.done()
, .fail()
, etc) or just waitfor the promise to fullfil using $.when()
.
当然,你可以得到这些的所有优点递延对象藏汉,比如增加更多的事件处理某些事情之后(.done()
,.fail()
,等),或者只是等待的承诺fullfil使用$.when()
。
回答by Trevor
You can set a callback in your ajax call:
您可以在 ajax 调用中设置回调:
$.ajax({
url: "foo1.html"
}).done(function() {
alert('Done!');
});
回答by sdespont
I would set variable before AJAX call and reset it in the success callback like that :
我会在 AJAX 调用之前设置变量并在成功回调中重置它,如下所示:
var isRunning = true;
$.ajax({
url: url,
success: function(resp){
isRunning = false;
}
});
回答by abhisek
I had similar issues. I used this code:
我有类似的问题。我使用了这个代码:
var isRunning = false; // whether ajax call is running
if(isRunning==false){
isRunning = true;
$.ajax({
// do your stuff
// make sure you set
isRunning = false;
// on success
});
}
回答by Pow-Ian
Wrap the call in a try catch.
将调用包装在 try catch 中。
if the call to 'foo1' fails because the method does not exist on the server, in the catch call foo two and then three all the way down until you have exhausted all your fall backs.
如果对 'foo1' 的调用失败,因为该方法在服务器上不存在,则在 catch 调用 foo 2 和 3 一直向下,直到您用尽所有回退。
If you know the method exists and think it will fail, then set a status on it that can be returned if the server fails then handle the return in the ajax callback.
如果您知道该方法存在并认为它会失败,则在其上设置一个状态,如果服务器失败则可以返回该状态,然后在 ajax 回调中处理返回。