简体   繁体   中英

Detect when XMLHttpRequest has connected

I'm trying to detect when a long-running XMLHttpRequest has actually connected to the server.

Right now, when I listen for the readystatechange event, it only fires when the request is finished. My test server sends the headers and some data, and after a long timeout (10s), it finishes the request. The XHR only fires events at the very end, and then it does one for each of the following states back-to-back: HEADERS_RECEIVED, LOADING, DONE.

Here is my browser code:

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function(evt) {
    console.log('Request is now in state ' + xhr.readyState);

    if(xhr.readyState === xhr.HEADERS_RECEIVED) {
        console.log('Request has started');
    }
    if(xhr.readyState === xhr.DONE) {
        console.log('Request is finished');
    }
};
xhr.send(null);

How can I detect when the headers have ACTUALLY been received? I'm assuming that I can't detect when the request starts, based on what's available in the API.

So far, I've come up with the following:

  • Set request method to POST
  • Send some data when the request is opened eg xhr.send('something')
  • Listen for the xhr.upload.onload callback

Like this:

xhr.upload.onload = function(evt) {
    console.warn('Request has started');
};

This only works in Firefox and Safari though. Not Chrome or IE.

The XMLHttpRequest object has 5 readystates

  • 0 = uninitialized
  • 1 = loading
  • 2 = loaded
  • 3 = interactive
  • 4 = complete

You are just checking two of them in your code. Also you should be using an else if for efficiency.

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