2012-09-11 109 views
1

我有一些PHP從MySQL數據庫生成從數據的JSON對象JSON對象內它

$addressData = mysql_query("SELECT * FROM address WHERE ContactID = $contactID")or die("<br/><br/>".mysql_error()); 

while($r = mysql_fetch_assoc($addressData)){ 
    $rows[] = array('data' => $r); 
} 

// now all the rows have been fetched, it can be encoded 
echo json_encode($rows); 

這將生成以下JSON對象:

[ 
    {"address": 
    {"AddressID":"10011","AddressType":"Delivery","AddressLine1":"4 Caerleon Drive","AddressLine2":"Bittern","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 5LF","Country":"United Kingdom","ContactID":"10011"}}, 
    {"address": 
    {"AddressID":"10012","AddressType":"Home","AddressLine1":"526 Butts Road","AddressLine2":"Sholing","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"}} 
] 

當接收它返回到Ajax並通過以下方式運行它:

$.each(data, function(key, val) { 
    string =string + "Key: " + key + " Value:" + val + "<br />"; 
}); 

它打印以下內容:

鍵:0值:[對象的對象]

鍵:1的值:[對象的對象]

有關如何我可以在數據內的關鍵01訪問的對象的任何想法?

回答

2

這是因爲對象的默認toString實現在連接到String對象時導致「[object Object]」。您可以訪問VAL對象的字段像往常一樣,例如:

val.data.AddressID 

這樣的:

$.each(data, function(key, val) { 
    string += "Key: " + key + " Value:" + val.data.AddressID + "<br />"; 
}); 

請注意在環路VAL上面是{「數據」:... } JSON代碼的一部分,這就是爲什麼你需要指定val.data。可以訪問裏面的部分地址數據。

此外,你可以簡單地刪除數據嵌套級別,導致JSON佈局類似:

[ 
    {"AddressID":"10011","AddressType":"Delivery","AddressLine1":"4 Caerleon Drive","AddressLine2":"Bittern","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 5LF","Country":"United Kingdom","ContactID":"10011"}, 
    {"AddressID":"10012","AddressType":"Home","AddressLine1":"526 Butts Road","AddressLine2":"Sholing","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"} 
] 

使用這個PHP代碼:

while($r = mysql_fetch_assoc($addressData)){ 
    $rows[] = $r; 
} 

然後,你可以訪問迴路中的地址數據字段如下:

$.each(data, function(key, address) { 
    string += "Key: " + key + " Value:" + address.AddressID + "<br />"; 
}); 
+0

否,因爲'val'是{data:{}}對象。他應該改變他的json的格式並去除數據:嵌套 –

+0

同意,數據字段的嵌套級別是無用的,我會將其添加到答案中。 –

1

我會改變你的json的佈局,你不需要嵌套。嘗試:

[ 
    {"AddressID":"10011","AddressType":"Delivery",...}, 
] 

,那麼你可以遍歷返回值與主要=> VAL數組,其中val將成爲對象,因爲現在,val是抱着你要的對象的對象...

+0

很好的建議。只要改變'$ rows [] = array('data'=> $ r);'到'$ rows [] = $ r;'和你的舊代碼就可以正常工作。 –