0
我正在使用ajax調用服務器並獲取一些用戶數據。服務器返回格式化像下面的數組:如何使用jquery訪問多維數組中的數據?
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?
您需要訪問嵌套數組:'chart_data'是一個數組,它具有有'data'屬性元素。所以你需要另一個嵌套循環 – trincot
@trincot謝謝我試過這個。我得到一個錯誤,讀取'未捕獲的TypeError:item.chart_data.forEach不是函數' – kevinabraham
JSON輸出來自哪裏? PHP?語法不正確。如果你在你的問題中包含你在執行'console.log(JSON.stringify(result))'時得到的輸出將會很有用。這樣我們將看到正確的JSON。 – trincot