【问题标题】:How to access a variable initialized within an Ajax callback function?如何访问在 Ajax 回调函数中初始化的变量?
【发布时间】:2019-05-18 20:07:06
【问题描述】:

请提供帮助。

我正在尝试访问在 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:对象 日期: [] ID:数组(0) 长度:0 原型:数组(0) 原型:对象

【问题讨论】:

    标签: javascript jquery ajax datatables


    【解决方案1】:

    这里的问题是 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);

    【讨论】:

      猜你喜欢
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-14
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 2016-09-23
      相关资源
      最近更新 更多