【发布时间】:2021-09-05 09:01:51
【问题描述】:
我想在 ajax 调用之间存储数据,以便我可以将累积的数据保存在一个对象中。 我可以获取每个调用的数据,但我无法将数据累积到一个完整的数组中。
我创建了dataAccumulator () 函数,这样当我调用accumData.append 时,可以将单个调用的数据推送到持有者数组。
无论我在哪里声明或调用函数,我都会不断收到错误 Cannot read property 'append' of undefined 或 Uncaught TypeError: dataAccumulator is not a function...
这是代码:
var inter;
var dataAccumulator = dataAccumulator(); //object of interest
function startTempMonit()
{
$(document).ready(function()
{
time= 0;
inter = setInterval(function()
{
$.ajax // ajax call starts
({
//not relevant for the question. arguments removed...
})
.done(function(data) {
//problem here. data is foreach call.
//I would like to accumulate each of the data to handle the whole here.
dataAccumulator.append(data);
});
time= time + 0.5;
}, 500)
});
};
function dataAccumulator () {
let accumData = [];
console.log("accumData function created")
function append(data) {
accumData.push(data);
console.log(accumData); //log the accumulated data each time
}
this.append = append;
};
我想我的问题在于 js 作用域。我想在 ajax 调用 .done 中保留我的 accumData 数组。这就是我的问题的总结。
【问题讨论】:
-
你的名字有问题。您有两个名为
dataAccumulator的实体,变量和函数。然后你调用accumData()作为函数,但是没有这样的函数 -
谢谢,这是一个错字,因为我在将代码粘贴到问题帖子时将名称更改为函数。已更正
标签: javascript ajax scope