简体   繁体   中英

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 ? 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.

Use this inside the function to reference the object.

All you should do is using this keyword or changing your code like 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:

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

then you should change the Run function like:

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(target, xml, Run);

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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