【发布时间】:2011-06-08 17:44:42
【问题描述】:
我正在使用 JSON 和 javascript 从连接到数据库的 php 文件中检索数据。这就是我的 php 代码的样子:
while($row = $stmt->fetch_assoc()) {
$data[] = $row;
}
header("Content-type: text/plain");
echo json_encode($data,true);
这是我的 Javascript:
var displayfeeds = new ajaxObject('ajax/users/display.feeds.php');
displayfeeds.callback = function (responseText,status) {
var feed = JSON.parse(JSON.stringify(responseText));
$("#feeds-feedback").html(feed);
}
displayfeeds.update();
当我运行它时,它会打印出一个这样的数组:
[
{
"userID":"39160902151",
"content":"bar bar bar bar",
"published":"2011-06-07 10:33:35"
},
{
"userID":"5896858666",
"content":"foo foo foo foo foo",
"published":"2011-06-06 22:54:51"
}
]
我的问题是:我该如何显示“userID”和“content”? 我真的很挣扎。我是 JSON 新手。
【问题讨论】:
-
无需对 JSON 进行双重编码,摆脱
JSON.stringify()调用。JSON.strigify()是等效于 PHP 命令json_encode()的 JavaScript。由于您将其作为字符串接收,因此无需在 JS 中执行此操作。JSON.parse()接受 JSON 字符串并将其转换为对象,PHP 有一个名为json_decode()的等效函数,如果您将 JSON 字符串传递回 PHP,您将使用该函数。