简体   繁体   中英

Checking jQuery AJAX Request Status

i do 2 different ajax request via jQuery and i have to check the other one is active or not. How can i do that ?

one of example from my ajax requests:

active_project_categories_ajax = $.ajax(
{
    url: "/ajax/get_skill_list",
    dataType: 'json',
    ......
});

i need something like that: active_project_categories_ajax.status()

since you are getting back the XMLHttpRequest object, you can always look at

active_project_categories_ajax.readyState
active_project_categories_ajax.status

the readyState needs to be 4 for it to be completed (success or error). so if it is less than 4, then it is still active.

this is the readyState:

// states
  const unsigned short UNSENT = 0;
  const unsigned short OPENED = 1;
  const unsigned short HEADERS_RECEIVED = 2;
  const unsigned short LOADING = 3;
  const unsigned short DONE = 4;

quoted from: http://www.w3.org/TR/XMLHttpRequest/#the-xmlhttprequest-interface

You cannot look at the status before readyState becomes 4. otherwise there may be an exception raised. (actually, i wrote a php file that return 1MB of data... and when the readyState was 3, the status was also 200. i suspect the status would be 200 if the readyState stopped at 2 as well).

You'd do that by subscribing to AJAX events and updating a status indicator:

var status;

$.ajax({
   beforeSend: function(){
     status = 1;
   },
   complete: function(){
     status = 2;
   }
   // ...
});

You're almost there, status is a property of XMLHttpRequest , and not a function. jQuery.ajax returns an object of XMLHttpRequest . Hold on to this as you're already doing:

var req = $.ajax(..);

Then call status on that object when needed, not status()

req.status

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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