2013-01-23 38 views
1

我從php/mysql數據庫查詢中獲取json多維數組(作爲$ .ajax調用的成功函數中的「數據」)。 PHP腳本將它發送到JavaScript文件,如下所示:如何在多維JSON數組中顯示值

header('Content-Type: application/json'); 
echo json_encode($arr); 

查詢可以從數據庫返回一條或多條記錄。

console.log(數據)似乎只給我在「父」數組中的第一個「子」數組。下面是在控制檯:

[{id:114, branchStateCovered:MN, branchCountyCovered:Aitkin,…},...] 
    0: {id:114, branchStateCovered:MN, branchCountyCovered:Aitkin,…} 
    1: {id:115, branchStateCovered:MN, branchCountyCovered:Benton,…} 
    2: {id:116, branchStateCovered:MN, branchCountyCovered:Carlton,…} 
    3: {id:117, branchStateCovered:MN, branchCountyCovered:Chisago,…} 
    4: {id:118, branchStateCovered:MN, branchCountyCovered:Cook,…} 
    5: {id:119, branchStateCovered:MN, branchCountyCovered:Crow Wing,…} 
    6: {id:120, branchStateCovered:MN, branchCountyCovered:Isanti,…} 
    7: {id:121, branchStateCovered:MN, branchCountyCovered:Itasca,…} 
    8: {id:122, branchStateCovered:MN, branchCountyCovered:Kanabec, branchZipCodesCovered:56358, 55051} 
    9: {id:123, branchStateCovered:MN, branchCountyCovered:Lake,…} 
    10: {id:124, branchStateCovered:MN, branchCountyCovered:Mille Lacs,…} 
    11: {id:125, branchStateCovered:MN, branchCountyCovered:Pine,…} 
    12: {id:126, branchStateCovered:MN, branchCountyCovered:Saint Louis,…} 
    13: {id:127, branchStateCovered:WI, branchCountyCovered:Douglas,…} 

在不同的$就呼叫我訪問什麼始終是一個一維數組

$('label#branchName').text(data['name']); 
$('label#branchAddress').text(data['address']); 
etc... 

但在這種情況下,我需要遍歷每個陣列並以與上述類似的方式顯示其每個值。

我發現this SO post,但它看起來像帖子作者創建數組的方式,他知道每個「孩子」數組的「名稱」(生產者)。也許我的答案是在那篇文章中,我只是沒有看到它。

如何獲取輸出的多維數組並循環顯示每個數組的數組到表中 - 或者我想在HTML端使用它的任何東西?

+1

看到服務器返回的將是令人難以置信的有益的實際JSON。 –

+0

@Anthony:我的OP中以「Object {...」開頭的代碼就是我在控制檯中獲得的代碼。如果有辦法獲得更多,我不知道。我怎麼做? – marky

+0

如果您使用的是Firefox瀏覽器的開發人員工具或[Firebug](http://getfirebug.com),所有通過按F12鍵訪問的工具都可以查看AJAX請求及其響應。 –

回答

3

success回調您$.ajax()通話,data是數組,所以你可以使用$.each()來遍歷它:

$.each(data, function(index, element) { 
    // use individual element (an object) here, i.e. element.id to get the id 
}); 
+0

這個伎倆! $ .each(data,function(index,element){ \t console.log(element ['branchStateCovered']); });是我用來獲得「子」數組的值之一。謝謝你,安東尼 – marky