【问题标题】:jQuery Ajax jSON set variable array value to inside ajax JSONjQuery Ajax jSON 将变量数组值设置为 ajax JSON
【发布时间】:2018-09-20 07:49:09
【问题描述】:

我很困惑将具有数组值的变量设置为 ajax json。

我在 JS 上有这个变量:

var complaintsData = [
    { complaint: "Pizza is cold", count: 780 },
    { complaint: "Inadequate cheese quantity", count: 120 },
    { complaint: "Not baked properly", count: 52 },
    { complaint: "Delayed delivery", count: 1123 },
    { complaint: "Damaged delivery", count: 321 },
    { complaint: "Incorrect billing", count: 89 },
    { complaint: "Wrong size delivered", count: 222 }
];

现在我需要从 DB 中获取变量数组值。 然后我有 ajax 从 db 获取数据:

setInterval(function()
{
    $.ajax(
    {
        url: "load2",
        type: "POST",
        dataType: "JSON",
        success: function (jsonStr)
        {
            for(var i=0; i<jsonStr.complaint.length; i++)
            {
                var complaintsData = [
                    { complaint: jsonStr.complaint[i], count: jsonStr.count[i] }
                ];
            }
        }
    });
}, 3000);

我试图运行上面的代码,但它不起作用。

我的问题,如何将var complaintsData 设置为内部 ajax 加载?

【问题讨论】:

  • 您能否在您的问题中也发布来自服务器的 jsonStr 数据?另外,您是要更新投诉数据数组还是只想替换为较新的数据?
  • 嗨@SumodhNair 我更新了我的问题

标签: jquery arrays json ajax


【解决方案1】:

为了给数组添加数据,需要使用push方法

 var complaintsData  = [];

    setInterval(function()
        {
            $.ajax(
            {
                url: "load2",
                type: "POST",
                dataType: "JSON",
                success: function (jsonStr)
                {   
                    for(var i=0; i<jsonStr.complaint.length; i++)
                    {
                        complaintsData.push ({ complaint: jsonStr.complaint[i], count: jsonStr.count[i] })
                    }
                }
            });
        }, 3000);

【讨论】:

  • 你能在循环结束后调试你的代码,看看有什么投诉数据吗?
  • 是否可以在 setInterval 上添加它?我试图删除 setInterval 并且它可以显示
  • 为什么要使用setInterval?您想每次 3 秒后调用服务器吗?
猜你喜欢
  • 1970-01-01
  • 2011-02-06
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
  • 1970-01-01
相关资源
最近更新 更多