ajax : function(typ,url,callback) {
if(window.XMLHttpRequest) {
var xml = new XMLHttpRequest();
}
if(window.ActiveXObject) {
var xml = new ActiveXObject("Microsoft.XMLHTTP");
}
xml.onreadystatechange = function(callback) {
if(xml.readyState == 4 && xml.status == 200) {
callback();
}
}
xml.open(typ,url,true);
xml.send();
}
}
//Function being called
window.onload = function() {
JS.ajax("GET","/server/chkEmail.php?email=email@email.com",function() {
alert(xml.responseText);
});
}
它抛出错误说:
未捕获TypeError:回调不是functionxml.onreadystatechange @ global.js:30
有什么想法吗?
我通过onreadystatechange函数传递数据变量并在回调函数中调用它来修复它。
ajax : function(typ,url,callback) {
if(window.XMLHttpRequest) {
var xml = new XMLHttpRequest();
}
if(window.ActiveXObject) {
var xml = new ActiveXObject("Microsoft.XMLHTTP");
}
xml.onreadystatechange = function(data) {
if(xml.readyState == 4 && xml.status == 200) {
var data = xml.responseText;
callback(data);
}
};
xml.open(typ,url,true);
xml.send();
}
}
window.onload = function() {
JS.ajax("GET","/server/chkEmail.php? email=jonwcode@gmail.com",function(data){
alert(data);
});
}
答案 0 :(得分:0)
试试这样:
xml.onreadystatechange = function() {
if (xml.readyState == 4 && xml.status == 200) {
callback();
}
};
请注意,onreadystatechange
函数不带任何参数,而在代码中,您传递了一个名为callback
的参数,该参数将覆盖callback
变量。外部范围。
更新:
看起来你没有正确确定xml
变量的范围,并且它在你的AJAX回调中不可用。我强烈建议您阅读有关javascript变量范围的更多信息。以下是如何使xml
变量可见:
var xml = null;
if (window.XMLHttpRequest) {
xml = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xml = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xml == null) {
alert('Sorry, your browser doesn\'t seem to support AJAX - please upgrade to a modern browser');
} else {
xml.onreadystatechange = function() {
if(xml.readyState == 4 && xml.status == 200) {
var data = xml.responseText;
callback(data);
}
};
xml.open(typ,url,true);
xml.send();
}