Javascript readyState如预期的那样时出现XHR状态错误
我正在编写一个JavaScript程序,它需要大量使用XHR方法。我使用的是异步样式。这是我的核心Javascript readyState如预期的那样时出现XHR状态错误,javascript,xmlhttprequest,Javascript,Xmlhttprequest,我正在编写一个JavaScript程序,它需要大量使用XHR方法。我使用的是异步样式。这是我的核心 global = {}; global.xhr = {}; global.xhr.requestQueue = []; global.xhr.responseQueue = []; xhr = new XMLHttpRequest(); xhr.first = true; xhr.on
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开发控制台会打印一系列错误,如下所示
Uncaught InvalidStateError:未能对“XMLHttpRequest”执行“发送”:必须打开对象的状态。
尽管对xhr.send()。这让我感到困惑,因为我的看法表明,当xhr.readyState
是1
时,我调用了xhr.send()
,相当于XMLHttpRequest.OPENED
,但我收到了一个关于情况并非如此的投诉
顺便说一下,所有请求都成功完成,global.xhr.responseQueue
将填充预期的响应信息。这些都是域内请求。是否使用Node.js?如果是这样,你必须添加适当的标签。好问题。否。这包含在从.html文件到用户浏览器的HTTP响应中。我省略了node.js
标记,因为情况就是这样。xhr
是否有意成为全局变量?这看起来是一个非常糟糕的主意。是的,xhr
旨在实现全球化。为什么这是个坏主意?我在这里使用的API都没有使用具有该名称的全局变量。