我试图在第一次不使用jQuery的情况下向模块添加ajax方法。我的方法.jax()
上出现以下错误:未捕获的InvalidStateError:无法在'XMLHttpRequest'上执行'send':对象的状态必须为OPENED。
我不知道如何解决这个问题。这是我的模块和一些简单的HTML。
var Test = (function (el) {
function InnerTest () {
this.el = el;
//Capital letters indicate a constant that should not change.
this.PARA = 'p'
this.init();
};
InnerTest.prototype.init = function () {
this
.createChildren()
.runIt()
.jax();
};
InnerTest.prototype.createChildren = function () {
this.para = this.el.querySelectorAll(this.PARA);
return this;
};
InnerTest.prototype.runIt = function () {
var len = this.para.length;
for (var i = 0, item; item = this.para[i]; i++) {
//test if browser supports the classList method else use className to add class.
if (item.classList) {
item.classList.add(item.textContent)
}
else {
item.className += ' ' + item.textContent
}
console.log( item );
console.log( item.classList );
}
return this;
};
InnerTest.prototype.jax = function () {
var self;
var request = new XMLHttpRequest();
request.open = ('GET', 'https://api.github.com/users/xxxxxxxxx', true);
request.send();
request.onload = function () {
data = JSON.parse(this.reponse);
console.log( data );
};
return this;
};
return InnerTest;
}( document.querySelector('.box') ));
(function () {
new Test();
}());
这是HTML:
<div class="box">
<p>One</p>
<p>Two</p>
<p>Three</p>
</div>
答案 0 :(得分:7)
open是一个方法,而不是属性
request.open = ('GET', 'https://api.github.com/users/xxxxxxxxx', true);
^^^
应该是
request.open('GET', 'https://api.github.com/users/xxxxxxxxx', true);
^^^
答案 1 :(得分:2)
你错过了一些作品。看看这个example。你应该调用方法。我只是在没有测试的情况下打字:
InnerTest.prototype.jax = function () {
var self;
var request = new XMLHttpRequest();
request.open('get', 'https://api.github.com/users/xxxxxxxxx', true);
request.onreadystatechange = function() {
if(xhr.readyState === 4) { // xhr.status === 200 not needed in your case
data = JSON.parse(request.reponse);
console.log( data );
}
};
request.send();
return this;
};
答案 2 :(得分:1)
不确定这是否是您的代码中的拼写错误,但是:
var request = new XMLHttpRequest;
应该是:
var request = new XMLHttpRequest();