我使用ajax对服务器进行调用并获取一些用户数据。服务器返回如下格式的数组:
array:6 [▼
0 => array:17 [▼
"id" => 334
"provider" => "some_provider"
"option_id" => "x124223"
"option_title" => "title"
"api_parameter" => "parameter"
"chart_title" => "title"
"chart_color" => "#6a76fc"
"chart_target" => "2220"
"chart_type" => "line"
"chart_size" => "4"
"chart_data" => array:7 [▼
239 => array:2 [▼
"data" => 2114
"created_at" => "14/August"
]
240 => array:2 [▼
"data" => 2114
"created_at" => "15/August"
]
241 => array:2 [▶]
242 => array:2 [▶]
243 => array:2 [▶]
244 => array:2 [▶]
245 => array:2 [▶]
]
"average" => 2122.0
"current" => array:2 [▶]
"last" => array:2 [▶]
"current_status_icon" => "md-trending-neutral"
"current_status_color" => "#3DDCF7"
"status_message" => "hmm... The needle didnt move."
]
1 => array:17 [▼
"id" => 345
"provider" => "some_other_provider"
"option_id" => "x124"
"option_title" => "Title"
"api_parameter" => "parameter"
"chart_title" => "title"
"chart_color" => "#6A76FC"
"chart_target" => "Set a target"
"chart_type" => "line"
"chart_size" => "4"
"chart_data" => array:7 [▼
202 => array:2 [▼
"data" => 5
"created_at" => "13/August"
]
203 => array:2 [▼
"data" => 5
"created_at" => "14/August"
]
204 => array:2 [▶]
205 => array:2 [▶]
206 => array:2 [▶]
207 => array:2 [▶]
208 => array:2 [▶]
]
"average" => 5.0
"current" => array:2 [▼
"data" => 5
"created_at" => "16/August"
]
"last" => array:2 [▼
"data" => 5
"created_at" => "16/August"
]
"current_status_icon" => "md-trending-neutral"
"current_status_color" => "#3DDCF7"
"status_message" => "hmm... The needle didnt move."
]
然后尝试使用foreach循环
访问数组中的数据$.ajax({url: "/url/to/server", success: function(result){
result.forEach(function(item) {
console.log(item['chart_data']['data']);
});
}, complete: function() {
// Schedule the next request when the current one's complete
setTimeout(checkForUpdates, 3000);
}
});
});
但这只是记录undefined
。如何访问嵌套在每个顶级数组中的chart_data ?
您的数据结构不清楚,因为您共享的结构以PHP表示法输出,而不代表您在JavaScript中收到的JSON。
但我的猜测是,这将工作:
result.forEach(function(item) {
Object.keys(item.chart_data).forEach(function (key) {
console.log(item.chart_data[key].data);
});
});