我有一些 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 />";
});
打印以下内容:
Key: 0 Value:[object Object]
Key: 1 Value:[object Object]
关于如何访问数据中键 0
和 1
中的对象有什么想法吗?
最佳答案
这是因为 Object 的默认 toString 实现在连接到 String 对象时会导致“[object Object]”。您可以像往常一样访问 val 对象的字段,例如:
val.data.AddressID
像这样:
$.each(data, function(key, val) {
string += "Key: " + key + " Value:" + val.data.AddressID + "<br />";
});
请注意,上面循环中的 val 是 JSON 代码的 {"data": ...} 部分,这就是为什么您需要指定 val.data. 来访问部分里面的地址数据。
此外,您可以简单地删除 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 />";
});
关于php - 带有多个json对象的json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12365616/