AJAX XHR请求onReadyStateChange事件的顺序和次数澄清

时间:2016-11-18 01:02:43

标签: javascript ajax

我正在学习并尝试使用Python-Flask和Javascript编写一个简单的股票报价工具。

我特别想学习普通 Javascript。我的代码正在运行,但我不明白的是,当我在观看开发人员控制台时,在获得成功的console.log(响应)之前,我会收到3条错误消息。

只是代码在响应返回之前循环了3次,因此它记录了“错误”和“错误”。在最终返回200状态之前的每个时间?有人会向我解释或给我一篇好文章/帖子吗?

我的事件监听器:

document.getElementById("btn_quote").addEventListener("click", getQuote);

ajax电话:

function getQuote(e){
    e.preventDefault();
    var ticker = document.getElementById("ticker").value
    var shares = document.getElementById("shares").value
    var url = "/quote/"+ticker+"/"+shares

    // Fetch the latest data.
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState === XMLHttpRequest.DONE) {
            if (request.status === 200) {
                var response = JSON.parse(request.response);
                console.log(response);
            }
        } else {
            // TODO, handle error when no data is available.
            console.log('ERROR');
            return false;
        }
    };
        request.open('GET', url);
        request.send();
} 

3 个答案:

答案 0 :(得分:3)

它没有返回单独的HTTP状态代码,它返回不同的就绪状态。

更改您的console.log("ERROR");。致console.log(request.readyState);

然后你会看到它的报道内容和原因。

答案 1 :(得分:3)

我认为您应该使用响应的实际值检查readyState值。供您参考,以下是readyState的可能值:

0: request not initialized 
1: server connection established
2: request received 
3: processing request 
4: request finished and response is ready

所以你基本上可以将它检查为4:

var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState === 4) {
            //response statements
        } else {
            //error statements
        }
    };

答案 2 :(得分:1)

基本上,ajax调用将收到以下事件的通知,这些事件称为readyStateChange事件。

enter image description here

对于大多数情况,您曾经根据连接速度获得4个就绪状态更改(极少数情况下只有一个如果非常快),您应该检查它是否 4 表示现在已完成响应。

要检查请求是否已成功,您应该检查request.status === 200这意味着成功,并可以检查其他http status code是否有404500等错误



document.getElementById("btn_quote").addEventListener("click", getQuote);
document.getElementById("btn_quote_error").addEventListener("click", getQuoteError);

function getQuote(e){
    e.preventDefault();
    var ticker = document.getElementById("ticker").value;
    var shares = document.getElementById("shares").value;
    //var url = "/quote/" + ticker + "/" + shares;
    var url = 'http://stackoverflow.com/';

    // Fetch the latest data.
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
      console.log(request.readyState);
        if (request.readyState === XMLHttpRequest.DONE) {
            console.log(request.status);
            if (request.status === 200) {
                //var response = JSON.parse(request.response);
                //console.log(response);
            }
        } 
        //else {
            // TODO, handle error when no data is available.
            //console.log('ERROR');
            //return false;
        //}
    };
        request.open('GET', url, true);
        request.send();

  
}

function getQuoteError(e){
    e.preventDefault();
    var ticker = document.getElementById("ticker").value;
    var shares = document.getElementById("shares").value;
    //var url = "/quote/" + ticker + "/" + shares;
    var url = 'http://stackoverflow404.com/';

    // Fetch the latest data.
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
      console.log(request.readyState);
        if (request.readyState === XMLHttpRequest.DONE) {
            console.log(request.status);
            if (request.status === 200) {
                //var response = JSON.parse(request.response);
                //console.log(response);
            }
        } 
        //else {
            // TODO, handle error when no data is available.
            //console.log('ERROR');
            //return false;
        //}
    };
        request.open('GET', url, true);
        request.send();

  
}

<input type="text" id="ticker"/>
<input type="text" id="shares"/>
<input type="button" id="btn_quote" value="Get Quote" />
<input type="button" id="btn_quote_error" value="Get Quote Error" />
&#13;
&#13;
&#13;