【问题标题】:use a function to store each ajax call data使用一个函数来存储每个ajax调用数据
【发布时间】: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


【解决方案1】:

第一步始终是摆脱全局变量。第二步是使用事件而不是全局状态。

注册一个每次数据到达时调用的回调。然后在回调中处理数据。

function startTempMonit(callback) {
    var time = 0;
    return setInterval(function () {
        $.ajax({ 
            url: '....',
            data: '.....' + tiempo
            dataType: '.....',
        })
        .done(function (data) {
            console.log("received", data);
            callback(data);
        });
        time += 0.5;
    }, 500);
}

$(function () {
    var inter, accumData = [];
    
    $("#buttonStart").click(function () {
        inter = startTempMonit(function (data) {
            accumData.push(data);
            // do something, i.e. add it to a table or a chart
        });
    });
    $("#buttonStop").click(function () {
        clearInterval(inter);
    });
});

【讨论】:

    猜你喜欢
    • 2012-08-26
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 2015-01-25
    • 1970-01-01
    相关资源
    最近更新 更多