javascript - 如何访问在 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) 原型:对象
解决方案
这里的问题是该setTimeout
函数checkMachineState()
立即运行该函数,而不是等待 5 秒。
那是因为setTimeout
期待一个函数名(即checkMachineState
没有()
)。但是输入的是一个函数表达式(一个带有关闭的函数()
,javascript在遇到它时会运行并解析为一个值)。
但是您需要有括号才能传递参数odata
和INTERVAL
. 解决方案是将函数包装在匿名函数声明中(声明函数通常不会导致它运行),如下所示:
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);
推荐阅读
- react-native - 带有子菜单的 createStackNavigator
- python - 计算列中每一行的 len 并且只取一个尊重条件 Pandas Python
- javascript - Selenium Javascript Executor Click() 在实际点击页面之前搜索页面上的元素
- arrays - Powershell从foreach循环中的数组替换字符串
- c# - 2dArray 到 Json 字符串
- applepay - 设备库标识符是否随推送令牌而变化?
- php - 来自 WhereIn 的访问关系
- mongodb - 连接到另一个嵌套集合的 MongoDB 集合中的全文搜索
- android-recyclerview - 如何在 RecyclerView 中处理无效的 RealmList
- typescript - 如何在 Typescript 中检查二进制类型别名