2014-04-09 126 views
0

我想作爲參數傳遞一個通用函數爲onreadystatefunction,我該怎麼做,並訪問xmlhttpobj? 類似的東西:JavaScript AJAX回調函數作爲參數

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

你錯過了'var':你可以調用XMLHTTP的功能是這樣的。不要試圖讓它成爲全球。 – Bergi

回答

1

的功能將在XHR對象的readychange事件觸發的背景下被調用。

使用this函數內部引用該對象。

0

所有你應該做的是利用this關鍵字或更改你這樣的代碼:

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

其他方式傳遞xhr對象作爲參數:

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

那麼你應該改變運行功能如:

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

now前`httpObj`

xmlHttp(target, xml, Run); 

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