问题描述
我当前正在编写JavaScript Ajax类,并且遇到错误.在函数processRawData()中,我似乎无法使用this.xhr访问类变量xhr.我得到无法读取未定义的readyState的属性.我目前已通过在设置对onreadystatechange函数的引用时传递xhr值来解决此问题,但这似乎是不必要的,因为我应该能够访问xhr值而无需这样做./p>
I am currently writing a JavaScript Ajax class and have encountered an error. In the function processRawData() I can't seem to access the class variable xhr by using this.xhr. I get "cannot read property of readyState of undefined. I have currently fixed this problem by passing in the xhr value when setting the reference to the onreadystatechange function however that seems unneeded as I should be able to access the xhr value without doing so.
function Ajax()
{
this.xhr = this.createXmlHttpRequest();
}
Ajax.prototype.createXmlHttpRequest = function()
{
if (window.XMLHttpRequest) {
try {
return new XMLHttpRequest();
} catch (e) {
throw new Error("Couldn't create XmlHttpRequest : " + e);
}
} else {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
throw new Error("Couldn't create XmlHttpRequest : " + e);
}
}
}
Ajax.prototype.request = function(type, url, params, dataType, callback)
{
if (this.xhr.readyState === 0 || this.xhr.readyState === 4) {
var isGetWithParams = (type === "GET") ? ((params !== null) ? url + params : url) : url
this.xhr.open(type, isGetWithParams, true);
this.xhr.onreadystatechange = this.processRawData(dataType, callback);
var passInParams = (type === "GET") ? null : ((params !== null) ? params : null);
this.xhr.send(passInParams);
}
}
Ajax.prototype.processRawData = function(dataType, callback)
{
return function()
{
if (this.xhr.readyState === 4 && this.xhr.status === 200) {
switch (dataType) {
case "text":
var data = this.xhr.responseText;
break;
case "xml":
default:
var data = this.xhr.responseXML;
}
callback(data);
}
}
}
推荐答案
类似的问题可能是因为在processRawData()中您正在返回另一个函数并引用this.xhr.readyState,但是"this"现在引用了返回的函数而不是Ajax类.试试:
Looks like your problem might be because in processRawData() you are returning another function and referencing this.xhr.readyState, but 'this' now references the returning function and not the Ajax class. Try:
Ajax.prototype.processRawData = function(dataType, callback){
var that = this; //'that' references the current Ajax instance
return function()
{
if (that.xhr.readyState === 4 && that.xhr.status === 200) {...
这篇关于在onreadystatechange函数中访问类变量的Ajax类错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!