JavaScript AJAX回调函数作为参数

时间:2014-04-09 11:27:11

标签: javascript ajax

我想将通用函数作为参数传递给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"
   }

2 个答案:

答案 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);
});