我有一些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的值:[對象的對象]
有關如何我可以在數據內的關鍵0
和1
訪問的對象的任何想法?
否,因爲'val'是{data:{}}對象。他應該改變他的json的格式並去除數據:嵌套 –
同意,數據字段的嵌套級別是無用的,我會將其添加到答案中。 –