尝试实现自己的AJAX原型,而不是使用jQuery或其他。 我无法检索任何结果,断点,在某些行上设置不会触发:
问题在于下一部分:
为什么它未定义,如果我之前使用HttpXml
函数初始化init()
实例:
我正在尝试从下一个程序的其他部分发送请求:
var ajaxInstance = new GC3D.Ajax();
ajaxInstance.init();
var response = ajaxInstance.sendRequest({
HttpMethod: 'GET',
UrlEndpoint: '/SomeService?function=someFunctionName'
});
该原型的完整来源:
GC3D.Ajax = function() {
this.httpRequest = undefined;
this.listExceptions = undefined;
};
GC3D.Ajax.prototype.init = function() {
this.listExceptions = [];
if ( window.XMLHttpRequest ) this.httpRequest = new XMLHttpRequest();
else if ( window.ActiveXObject ) {
try {
this.httpRequest = new ActiveXObject( 'Microsoft.XMLHTTP' );
}
catch ( exception ) {
this.listExceptions.push( exception );
try {
this.httpRequest = new ActiveXObject( 'Msxml2.XMLHTTP' );
}
catch ( exception ) {
this.listExceptions.push( exception );
try {
this.httpRequest = new ActiveXObject( 'Microsoft.XMLHTTP' );
}
catch ( exception ) {
this.listExceptions.push( exception );
}
}
}
}
if ( !this.httpRequest ) {
console.error( 'Can\'t create a HTTP Request instance for AJAX! Possible problems:' );
console.error( this.listExceptions );
}
else this.httpRequest.onreadystatechange = this.getContentFromRequest;
};
GC3D.Ajax.prototype.sendRequest = function( properties ) {
if ( this.httpRequest !== undefined ) {
this.httpRequest.open( properties.HttpMethod, properties.UrlEndpoint );
this.httpRequest.send();
}
else throw 'HTTP Request instance isn\'t defined!';
};
GC3D.Ajax.prototype.getContentFromRequest = function() {
if ( this.httpRequest !== undefined ) {
if ( this.httpRequest.readyState === 4) {
if ( this.httpRequest.status === 200 ) return this.httpRequest.responseText;
else console.log( 'There was a problem with the request in GC3D.Ajax.' );
}
}
};
GC3D.Ajax.prototype.get = function() {
return this.httpRequest;
};
什么是不正确的以及为什么它不在上面那条线上开火?
由于
答案 0 :(得分:0)
问题在于this
上下文失败:
else this.httpRequest.onreadystatechange = this.getContentFromRequest;
当我申请该事件时,其上方的功能已失去此实例。
让我们想象一下,我们不知道确切的函数名称,它将是一个匿名函数:
this.someEvent.onSomething = function( item ) { ... };
由于范围定义{}
,它在匿名函数中失败,关闭了this
的可见空间。
因此,当我将某些部分更改为:
时,我的代码就出现了类似的问题GC3D.Ajax.prototype.getContentFromRequest = function() {
if ( this.readyState === 4 ) {
if ( this.status === 200 ) return this.responseText;
else console.log( 'There was a problem with the request in GC3D.Ajax.' );
}
};
现在代码正在运行!