Jquery POST未填充数组
Jquery POST not populating array
我正在尝试用引用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
$.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,
});
将你的逻辑移到那里,如果你不能把你的逻辑放在一个函数中,并在你完成的回调中调用该函数。
相关文章:
- 将数据推送到数组填充 jqGrid
- 使用 JSON 数组填充输入字段
- 用Javascript中的JSON数组填充HTML
- 动态生成的表格 - 使用数组填充TD值
- 使用数组填充if语句值
- AngularJS:用两个JSON数组填充复选框列表,最初检查了一个数组中的一些项
- 为什么不是't ng表将数据从数组填充到表中
- 在javascript中用数组填充对象
- 高图表 - 从数组填充数据
- 如何从下拉列表中由可观察数组填充的选定项中检索完整对象
- 使用 JavaScript 数组填充下拉选择框
- Javascript array.length 为 0,但数组填充了 40 个项目
- 使用 JSON 数组填充图表
- 数组填充外部函数 - 不可访问的成员
- 用 javascript 数组填充 struts2 select 标签
- 用服务器数组填充 jquery 数组
- 如何使用 json 数组填充 Rails 下拉菜单
- 在用数组填充初始化的数组上使用数组映射的意外行为
- JavaScript 风格的数组填充在 Java 中
- 如何使用 javascript 数组填充 html 标题