简体   繁体   English

JavaScript AJAX回调函数作为参数

[英]JavaScript AJAX Callback Functions as Parameter

I would like to pass as parameter a generic function to be the onreadystate function , how can i do that and acess the xmlhttpobj ? 我想将一个通用函数作为参数传递给onreadystate function ,我该怎么做并访问xmlhttpobj Something like that: 像这样:

    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"
   }

The function will be called in the context of the XHR object that the readychange event fires on. 该函数将在readychange事件触发的XHR对象的上下文中调用。

Use this inside the function to reference the object. 在函数内部使用this来引用对象。

All you should do is using this keyword or changing your code like this: 您应该做的就是使用this关键字或像这样更改代码:

function Run (){
   if (this.readyState==4 && this.status==200){
        //do a lot of things in "Place"
   }
}

the other way is passing the xhr object as an argument: 另一种方法是将xhr对象作为参数传递:

httpObj.onreadystatechange = function(){
    readyfun(this);
};

then you should change the Run function like: 那么您应该更改Run函数,例如:

function Run(httpObj){
   if (httpObj.readyState==4 && httpObj.status==200){
        //do a lot of things in "Place"
   }
}

now you could call the xmlHttp function like this: 现在您可以像这样调用xmlHttp函数:

xmlHttp(target, xml, Run);

or 要么

xmlHttp(target, xml, function(httpObj){
    Run(httpObj);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM