如果请求失败,为什么XMLHttpRequest响应返回null?

时间:2017-02-04 04:43:07

标签: javascript ajax xmlhttprequest

我试图处理来自XMLHttpRequest的不同响应代码。但是,如果我得到200以外的任何内容,则响应对象始终为空,并且不打印预期状态(例如403,404等)。这是我的代码:

 var xhttp = new XMLHttpRequest();
 xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4)
    {
        if (xhttp.status == 200) {
           console.log(xhttp.status);
        }else{
            console.log(xhttp.status);

        }
    }
};

xhttp.open('GET', url, true);
xhttp.send();

工作时的控制台输出:

200

出于任何原因失败的控制台输出:

0

例如,对于错误代码400,控制台将显示以下内容:

  

script.js:11
2script.js:55 GET
  https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=eaf6455bd8eb4f11a1f08923b811081e&q=1%&%%&begin_date=1234&end_date=123 400(nginx / 1.10.2)
searchQuery @ script.js:55
reader.onload @   script.js:14
index.html:1 XMLHttpRequest无法加载   https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=eaf6455bd8eb4f11a1f08923b811081e&q=1%&%%&begin_date=1234&end_date=123。   No' Access-Control-Allow-Origin'标题出现在请求的上   资源。起源' null'因此不允许访问。响应   有HTTP状态码400.

我更喜欢在纯Javascript中执行此操作,因此请不要建议jquery

1 个答案:

答案 0 :(得分:1)

如果唯一目的是处理不同的错误代码,您可以尝试

    var xhttp = new XMLHttpRequest();
    xhttp.onload = function() {

        if (xhttp.status == 200) {
           console.log(xhttp.status);
        }else{
            console.log(xhttp.status);
        }

    };

    xhttp.open('GET', url, true);
    xhttp.send();