Javascript 如何访问在Ajax回调函数中初始化的变量?
请帮忙 我试图访问在JQuery DataTable()函数外部声明的对象变量。我提供了Ajax对象的设置,其中一个回调函数在请求成功时完成执行。由于不推荐使用async:false,我决定使用setTimeout()从外部的回调函数访问初始化的变量。请参阅我的代码以澄清我的问题Javascript 如何访问在Ajax回调函数中初始化的变量?,javascript,jquery,ajax,datatables,Javascript,Jquery,Ajax,Datatables,请帮忙 我试图访问在JQuery DataTable()函数外部声明的对象变量。我提供了Ajax对象的设置,其中一个回调函数在请求成功时完成执行。由于不推荐使用async:false,我决定使用setTimeout()从外部的回调函数访问初始化的变量。请参阅我的代码以澄清我的问题 var odata = { ids: [], dates: [] }; var table = $("#schedule"); table.DataTable({ ajax: { url: "/api/Ma
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
调试器显示了以下内容
小田:对象
日期:[]
ID:数组(0)
长度:0
proto:数组(0)
proto:Object这里的问题是
setTimeout
函数正在立即运行函数checkMachineState()
,而不是等待5秒
这是因为setTimeout
需要一个函数名(即只需checkMachineState
而不需要()
)。但是输入的是一个函数表达式(一个关闭()
的函数,当遇到该函数时,javascript将运行该函数并解析为一个值)
但是您需要有括号才能传递参数odata
和INTERVAL
。解决方案是将函数包装在匿名函数声明中(声明函数通常不会导致其运行),如下所示:
setTimeout(()=>{checkMachineState(odata,INTERVAL)},5000)代码>
运行下面的代码以了解我的意思:
console.log(“启动”);
setTimeout(console.log(“由于()而立即运行”),10000//即使延迟是10秒
setTimeout(()=>console.log(“这在触发前等待5秒”),5000代码>