如何访问在Ajax回调函数中初始化的变量?

 收藏

请协助。

我正在尝试访问在JQuery DataTable()函数外部声明的对象变量。我已经为Ajax对象提供了设置,当请求成功时,其中的回调函数可以完成。由于不建议使用async:false,因此我决定使用setTimeout()从外部的回调函数访问初始化的变量。请查看我的代码以澄清我的问题。

var odata = {
 ids: [],
 dates: []
};
var table = $("#schedule");
table.DataTable({
 ajax: {
   url: "/api/MaintenanceSchedule",
   dataSrc: "",
   complete: function (data, status) {
       if (status === "success") {
         //some codes here
       }

       $("span.machineIds").each(function (index) {
           machineIds[index] = $(this).attr("data-machine-id");//here the array output all elements if you check with console.log()
       });

       $("span.lastMaintained").each(function (index) {
           lastMaintained[index] = $(this).attr("data-last-maintained");
        });

       //the odata properties below have assigned values as seen from the debugger window
       odata = {
          ids: machineIds,
          dates: lastMaintained
       };                           
   }

//some other codes ...

//outside DataTable object

var checkMachineState = function (odata, interval) {
  // some codes...
}

 const INTERVAL = 45000;

setTimeout(checkMachineState(odata,INTERVAL),5000);//odata properties are still not initialized as seen from the debugger

调试器显示如下

odata:对象 日期: [] ids:数组(0) 长度:0 原型:数组(0) 原型:对象

回复
  • 半神经 回复

    The problem here is the setTimeout function is running the function checkMachineState() immediately instead of waiting 5 seconds.

    That's because setTimeout is expecting a function name (i.e. just checkMachineState without the ()). But what is entered is a function expression (a function with closing (), which javascript will run when encountered and resolve to a value).

    But you need to have the parenthesis in order to pass the parameters odata and INTERVAL. The solution is to wrap your function within an anonymous function declaration (declaring a function normally will not cause it to run), like so:

    setTimeout(() => {checkMachineState(odata,INTERVAL)},5000);

    运行下面的代码,以了解我的意思:

    console.log("start");
    setTimeout(console.log("This runs immediately because of the ()"),10000); //even if delay is 10 seconds
    
    setTimeout(() => console.log("This waits 5 seconds before firing"), 5000);

    我已经用ES6箭头符号编写了上面的代码。您也可以将其编写为:

    setTimeout(function() {checkMachineState(odata,INTERVAL)},5000);