当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - 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
分享给朋友:
您可能感兴趣的文章:
随机阅读: