[英]Passing Function As Parameter For Callback
我試圖將函數作為參數傳遞給引用泛型XMLhttp變量的requestDataFromServer函數。
我已經閱讀了有關綁定功能並使用“ THIS”的信息,但無法使其正常工作。
我在這里有通用的XMLHTTP函數requestDataFromServer,我希望向它傳遞一個asp url和一個回調函數,以在觸發onreadystatechange時運行它。
function requestDataFromServer(aspLink, callbackFunction) {
var genericxmlhttp = new XMLHttpRequest();
genericxmlhttp.onreadystatechange = function () {
if (this.readyState==4 && this.status==200) {
callbackFunction();
}
}
genericxmlhttp.open("GET",aspLink,true);
genericxmlhttp.send(null);
}
我想做的是在傳遞它之前在回調函數中引用genericxmlhttp對象,這樣我就可以對responseText進行處理。
case "job":
var aspLink = "/jobTree/asp/getJobTreeDetails.aspx?sqlCommand=Exec schd.get_job_details @job_id%3D" + this.getAttribute("id")
requestDataFromServer(aspLink, function() {
console.log(genericxmlhttp.responseText);
document.getElementById("cntDisplay").innerHTML = genericxmlhttp.responseText
});
我得到的錯誤是“ genericxmlhttp未定義”
有什么方法可以引用genericxmlhttp對象嗎?
該變量是requestDataFromServer
局部的,因此您不能在回調函數中引用它。
調用回調時將其作為參數傳遞。
function requestDataFromServer(aspLink, callbackFunction) { var genericxmlhttp = new XMLHttpRequest(); genericxmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { callbackFunction(this); } } genericxmlhttp.open("GET", aspLink, true); genericxmlhttp.send(null); } ... case "job": var aspLink = "/jobTree/asp/getJobTreeDetails.aspx?sqlCommand=Exec schd.get_job_details @job_id%3D" + this.getAttribute("id") requestDataFromServer(aspLink, function(genericxmlhttp) { console.log(genericxmlhttp.responseText); document.getElementById("cntDisplay").innerHTML = genericxmlhttp.responseText });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.