将函数作为参数传递给回调

时间:2019-06-07 16:24:45

标签: javascript parameters xmlhttprequest

我试图将一个函数作为参数传递给引用genericxmlhttp变量的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对象吗?

1 个答案:

答案 0 :(得分:1)

该变量是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

  });