简体   繁体   中英

Ajax onerror handler not working

In pure Javascript: I make an AJAX request.

The server is supposed to return a 410 error.

My code:

var ajax = new XMLHttpRequest();
ajax.onload = displayXML;
ajax.onerror = displayError;
ajax.open('GET', 'http://myurl.com/request?param=1&param=2', true);
ajax.send();

function displayError(e) {
    console.log(this.status);
}

function displayXML() {
    console.log(this.responseXML);
}

Problem is, the onerror function never gets called even when a HTTP 410 is returned. My console says that "GET .... 410 (Gone)" on the line which ajax.send() appears, but then it calls displayPopularity . How should I handle HTTP errors, if I can't use .onerror ? I mean, I could just roll the error handling into displayPopularity but I thought there was a more elegant solution.

I believe onerror is only for security issues (eg. cross-origin ) or errors in "config" ajax (front-end).

"HTTP errors" are not considered "errors", but "responses" from server.

XMLHttpRequest.onload is always executed, even if there is error in "http response":

Try onreadystatechange with if :

function displayXML()
{
    if (this.readyState == 4) //this line is equivalent to ajax.onload
    {
        if (this.status == 200) //Detect http status response (200 = Ok)
        {
           console.log(this.responseXML);
        } else {//If 200 <> status = HTTP error
           console.log(this.status);
       }
    }
}

var ajax = new XMLHttpRequest(); //Create obj
ajax.open('GET', 'http://myurl.com/request?param=1&param=2', true); //Config request
ajax.onreadystatechange = displayXML; //Add event
ajax.send(null); //Send request

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