如何访问AJAX回调函数中初始初始化的变量



请帮助。

我正在尝试访问jQuery datatable((函数之外声明的对象变量。我为AJAX对象提供了设置,其中已成功的回调函数完成了请求时执行的设置。由于exync: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 proto :数组(0( proto :object

这里的问题是setTimeout函数正在立即运行函数checkMachineState()而不是等待5秒。

那是因为setTimeout期望函数名称(即,只有checkMachineState没有()(。但是输入的是A 函数表达式(具有关闭()的函数,JavaScript遇到时将运行并解析为值(。

但是您需要具有括号才能传递参数odataINTERVAL。解决方案是将您的函数包装在匿名函数声明中(声明函数通常不会导致其运行(,例如:

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);

最新更新