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