当readyState与预期一样时,XHR状态错误

时间:2015-06-20 09:52:42

标签: javascript xmlhttprequest

我正在编写一个需要大量使用XHR方法的JavaScript程序。我正在使用异步样式。这是我所拥有的核心。

        global = {};
        global.xhr = {};
        global.xhr.requestQueue = [];
        global.xhr.responseQueue = [];

        xhr = new XMLHttpRequest();
        xhr.first = true;
        xhr.onreadystatechange = function() {
            //console.log(this.readyState);
            if(this.readyState == 4) {
                if(this.first) {
                    this.first = false;
                    global.carouselItems = parseInt(this.responseText);
                    global.onSlideCountReceived();
                } else {
                    global.xhr.responseQueue.push({status: xhr.status, responseText: xhr.responseText});
                    if(global.xhr.requestQueue.length > 0) {
                        xhr.open("GET", global.xhr.requestQueue[0]);
                        global.xhr.requestQueue.shift();
                    }
                }
            }
            if(xhr.readyState == 1) {
                xhr.send();
            }
        }
        //Code which adds a bunch of items to global.xhr.requestQueue
        xhr.open("GET","assets/carousel/items.php");

但是当我运行它时,Chrome Dev控制台会打印出一堆错误,如下所示。

Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.

尽管上面的代码段中只有xhr.send()的调用,但它包含在if语句中。这让我感到困惑,因为我看到它的方式表明我在xhr.send() xhr.readyState 1时拨打了XMLHttpRequest.OPENED,相当于global.xhr.responseQueue但我得到了投诉关于这不是这种情况。

顺便说一下,请求全部成功完成,Connection con = somehowGetYourConnection(); try { con.setAutoCommit(false); //query1 //... //some more stuff //... //query 2, inserting into the table of the reservation //... con.commit(); } catch(SQLException e) { //log somehow //... con.rollback(); //you will need somehow to tell your user that the reservation failed //... } 填充了预期的响应信息。这些都是域内请求。

0 个答案:

没有答案