简体   繁体   English

如何使用jQuery检查ajax调用是否存在?

[英]How to check if ajax call exists using jQuery?

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. 请不要告诉我再次测试foo == something My actual code is much, much more complicated, so please answer the question from the view of the ajax call. 我的实际代码要复杂得多,所以请从ajax调用的角度回答问题。

Is this possible at all? 这有可能吗?

I'm not sure if I understood you right, but jQuery will mix a Deferred object into its jXHR object 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/ 其他州被rejectedpending ,请参阅http://api.jquery.com/deferred.state/

Of course, you can get all advantages of those Deferred objects aswell, like adding more event handlers for certain things afterwards ( .done() , .fail() , etc) or just wait for the promise to fullfil using $.when() . 当然,你可以获得那些Deferred对象的所有优点,比如之后为某些事情添加更多的事件处理程序.done() .fail()等)或者只是等待使用$.when() .fail()的承诺$.when()

You can set a callback in your ajax call: 您可以在ajax调用中设置回调:

$.ajax({
  url: "foo1.html"
}).done(function() { 
  alert('Done!');
});

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;
    }
});

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
   });
}

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中然后是三个,直到你已经用尽所有后退。

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回调中的返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM