1

我有一些 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 对象]

关于如何访问键01数据中的对象的任何想法?

4

2 回答 2

2

这是因为 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 的原因。访问内部的部分地址数据。

此外,您可以简单地删除数据嵌套级别,从而生成如下 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 />";
});
于 2012-09-11T08:31:54.427 回答
1

我会改变你的 json 的布局,你不需要嵌套。尝试:

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

然后你可以用 key => val 将返回值迭代为一个数组,其中val将是对象,因为现在,val是持有你想要的对象的对象......

于 2012-09-11T08:36:44.207 回答