簡體   English   中英

JavaScript AJAX回調函數作為參數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM