[英]JavaScript AJAX Callback Functions as Parameter
我想将一个通用函数作为参数传递给onreadystate
function
,我该怎么做并访问xmlhttpobj
? 像这样:
function xmlHttp(target, xml, readyfunc) {
if (window.XMLHttpRequest) {
httpObj = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
if (httpObj) {
httpObj.onreadystatechange = readyfunc;
httpObj.open("POST", target, true);
httpObj.send(xml);
}
}
function Run (Place){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
//do a lot of things in "Place"
}
该函数将在readychange事件触发的XHR对象的上下文中调用。
在函数内部使用this
来引用对象。
您应该做的就是使用this
关键字或像这样更改代码:
function Run (){
if (this.readyState==4 && this.status==200){
//do a lot of things in "Place"
}
}
另一种方法是将xhr
对象作为参数传递:
httpObj.onreadystatechange = function(){
readyfun(this);
};
那么您应该更改Run函数,例如:
function Run(httpObj){
if (httpObj.readyState==4 && httpObj.status==200){
//do a lot of things in "Place"
}
}
现在您可以像这样调用xmlHttp函数:
xmlHttp(target, xml, Run);
要么
xmlHttp(target, xml, function(httpObj){
Run(httpObj);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.