首页 > 解决方案 > 如何访问在 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) 原型:对象

标签: javascriptjqueryajaxdatatables

解决方案


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

那是因为setTimeout期待一个函数名(即checkMachineState没有())。但是输入的是一个函数表达式(一个带有关闭的函数(),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);


推荐阅读