我有一些 PHP 可以从 MySQL 数据库中的数据生成 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 值:[object 对象]
键:1 值:[object 对象]
关于如何访问键0
和1
数据中的对象的任何想法?