我想将通用函数作为参数传递给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"
}
答案 0 :(得分:1)
该函数将在readychange事件触发的XHR对象的上下文中调用。
在函数内使用this
来引用对象。
答案 1 :(得分:0)
您应该做的只是使用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);
});