[英]Passing Function As Parameter For Callback
I'm trying to pass in a function as a parameter to the requestDataFromServer function that refers to the genericxmlhttp variable. 我试图将函数作为参数传递给引用泛型XMLhttp变量的requestDataFromServer函数。
I have read about the bind function and using "THIS" but have not been able to get it to work. 我已经阅读了有关绑定功能并使用“ THIS”的信息,但无法使其正常工作。
I have the generic XMLHTTP function requestDataFromServer here which I want to pass it an asp url and a callback function to be run once the onreadystatechange is fired. 我在这里有通用的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);
}
What I want to do is refer to the genericxmlhttp object in the callback function before passing it in so I can do something with the responseText. 我想做的是在传递它之前在回调函数中引用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
});
The error I get is "genericxmlhttp is not defined" 我得到的错误是“ genericxmlhttp未定义”
Is there any way to refer to the genericxmlhttp object? 有什么方法可以引用genericxmlhttp对象吗?
The variable is local to the requestDataFromServer
, so you can't reference it in the callback function. 该变量是
requestDataFromServer
局部的,因此您不能在回调函数中引用它。
Pass it as a parameter when calling the callback. 调用回调时将其作为参数传递。
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.