【问题标题】:Jquery POST not populating arrayJquery POST 未填充数组
【发布时间】:2016-05-19 17:42:34
【问题描述】:

我正在尝试使用引用 HighCharts 的 JSON 条目填充数组。

其中一个 JSON 对象是手动填充的,一个需要使用 PHP 帖子动态填充。 我一直在尝试使用回调函数将数据推送到数组,但似乎没有数据被推送。

我能够验证来自 PHP Post 的数据。 看起来它确实填充了数组,但是一旦 Jquery POST 函数完成,数组似乎就被清空了。

另外,我在 POST 中有一个 console.table 调用。这实际上正确地打印了数组。

您可以从下面的代码中看到,我使用了 console.table() 调用 发布后立即,它是空的。 但是在我接下来手动推送之后,数据数组现在包含用于手动 JSON 数组推送的数据。

有什么想法吗?

这是我的代码:

/* INITIAL ARRAY **************************************/
data_array = [];
var colors = Highcharts.getOptions().colors;
categories = ['Dynamic', 'Manual'];

/* FUNCTION TO PUSH TO ARRAY *****************************/
function push_toarray(cats,counts) {

    data_array.push({
        y: 10.38,
        color: colors[1],
        drilldown: {
            name: 'Dynamically Populated',
            categories: [cats],
            data: [counts],
            color: colors[1]
        }
    });       
}

/* PHP AND FOR LOOP FOR GETTING DATA *********************************************/


    $.post( "php/dt_charts.php")
        .done(function( data ) {
        var obj = jQuery.parseJSON(data);

        // To verify the values are returned
        console.log(obj.fe_det_name);  
        console.log(obj.fe_det_count);

        push_toarray(obj.fe_det_name, obj.fe_det_count);
        console.table(data_array);  // This prints the array correctly with both JSON objects inside
    });

    //console.table(data_array);  // This prints no data.

/* MANUAL DATA ARRAY *********************************************/


    data_array.push({
        y: 10.38,
        color: colors[1],
        drilldown: {
            name: 'Manually Populated',
            categories: ['Firefox v31', 'Firefox v32', 'Firefox v33', 'Firefox v35', 'Firefox v36', 'Firefox v37', 'Firefox v38'],
            data: [0.33, 0.15, 0.22, 1.27, 2.76, 2.32, 2.31, 1.02],
            color: colors[1]
        }
    })


console.table(data_array); // This prints only the manually populated array values

【问题讨论】:

  • 所以,问题是在“完成”函数内部填充了对象。但是当你离开这个函数时,所有的修改都消失了,它变成了空的?
  • 问题在于 javascript 是异步的,所以当您在发送帖子后尝试访问数组时,真正令人兴奋的是帖子在您的日志语句之后执行,这就是您得到空数据数组的原因
  • 解决方案是在 done 回调中编写您的代码,这样您就可以实际使用从您的帖子返回的值。

标签: javascript php jquery arrays highcharts


【解决方案1】:
  $.post( "php/dt_charts.php")
     .done(function( data ) {
    var obj = jQuery.parseJSON(data);

    // To verify the values are returned
    console.log(obj.fe_det_name);  
    console.log(obj.fe_det_count);

    push_toarray(obj.fe_det_name, obj.fe_det_count);
    console.table(data_array);  // This prints the array correctly with both JSON objects inside

<----- move your logic here,

});

将你的逻辑移到那里,如果你不能把你的逻辑放在一个函数中并在你的 done 回调中调用该函数。

【讨论】:

  • 谢谢莫尼克斯。经过一些测试,我得出了相同的结论。将逻辑移到 .done 函数内部是可行的。
猜你喜欢
  • 1970-01-01
  • 2023-02-02
  • 2018-06-15
  • 2019-04-26
  • 1970-01-01
  • 1970-01-01
  • 2016-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多