这个问题看起来很奇怪。我在同一个 aspx 文件中有一个 AJAX 辅助函数,并且 onreadystatechange 事件是这样处理的
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4)
//do some opp
}
这工作正常。我可以读取回调中的 xmlhttp 值。
我将 AJAX 辅助方法移至附加 js 文件。我创建了一个类似这样的方法
function AjaxHelper() {
this.GetValue = function(sData, sMethod, assembly, json, aSyncfunction) {
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
if (typeof(aSyncfunction) != "undefined" && aSyncfunction != null) {
xmlhttp.onreadystatechange = aSyncfunction
}
//Ajax open and send code here
}
}
现在我在 aspx 文件中创建一个回调函数并调用 AjaxHelper.GetValue() 函数
var callback=function(){
if (xmlhttp.readyState == 4)
//do some opp
}
AjaxHelper.GetValue("test","getTest()","UIhelper","",callback)
并且每次状态更改后都会成功调用回调函数,但我无法引用 xmlhttp 变量。 它总是未定义。
我虽然它会在 AJaxhelper 上下文中执行,但事实并非如此。
谁能告诉我如何解决这个问题
最佳答案
I though its going to execute in the AJaxhelper context, but its not.
没有。 JavaScript 是有词法作用域的。完成函数 GetValue
后,局部变量 xmlhttp
将无法再访问。如果函数作用域内没有闭包保留对 xmlhttp
的引用(如本例所示),则变量 xmlhttp
将永远消失。
您可能希望让闭包在 GetValue
中保留 xmlhttp
并将其传递给回调函数:
if (aSyncfunction) {
xmlhttp.onreadystatechange= function() {
aSyncfunction(xmlhttp);
};
}
或者您可以将对象分配给一个成员变量,例如 this.xmlhttp
,该变量对于对象内部和外部的其他函数都是可见的。
var xmlHttp
关于javascript - AJAX调用中的onreadystatechange事件问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1714408/