显示来自 php json_encode 的 json 数据?
我有这个 jquery 代码,它填充一个输入选择器,它应该显示如下:
$("#demo-input-pre-populated").tokenInput("http://shell.loopj.com/", {
prePopulate: [
{id: 123, name: "Slurms MacKenzie"},
{id: 555, name: "Bob Hoskins"},
{id: 9000, name: "Kriss Akabusi"}
]
});
当我尝试使用 php 从数据库中获取值时,如下所示:
prePopulate: [
<?
$responses = array();
$topicJSON=getQtopics($getQ);
while($row = mysql_fetch_array($topicJSON)){
$response = array(
'id' => $row['id'],
'name' => $row['name']
);
$responses[] = $response;
}
echo json_encode($responses);
?>
],
它显示这样的 json 数据:
prePopulate: [
[{"id":"1","name":"Dormitree"},
{"id":"1482","name":"carriage of goods"}]
],
但在 #demo-input- pre-populated"
输入我未定义,我认为它是因为 php 没有正确地回显 json,我该如何解决这个问题,谢谢:))
i have this jquery code which poplautes a input selector, which should display like this:
$("#demo-input-pre-populated").tokenInput("http://shell.loopj.com/", {
prePopulate: [
{id: 123, name: "Slurms MacKenzie"},
{id: 555, name: "Bob Hoskins"},
{id: 9000, name: "Kriss Akabusi"}
]
});
when i try get the vales from the database using php like this:
prePopulate: [
<?
$responses = array();
$topicJSON=getQtopics($getQ);
while($row = mysql_fetch_array($topicJSON)){
$response = array(
'id' => $row['id'],
'name' => $row['name']
);
$responses[] = $response;
}
echo json_encode($responses);
?>
],
which displays the json data like this:
prePopulate: [
[{"id":"1","name":"Dormitree"},
{"id":"1482","name":"carriage of goods"}]
],
but on the #demo-input-pre-populated"
input i get undefined, and i think its becuase php is not echoing the json propelrly, how can i fix this thanks :))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你查看两个 JS 输出,唯一的区别是,在从 PHP 输出的情况下,你有两个额外的方括号
[]
- 所以你正在创建一个 JSON 数组的数组在这种情况下,您所需要的只是一个 JSON 对象数组。去掉
prePopulate
的封闭[]
,因为json_encode
已经为您执行此操作:If you look the two JS outputs, the only difference is that you have two extra enclosing square-brackets
[]
in the case where you output from PHP - so you're making an array of array of JSON objects in that case while all you need is an array of JSON objects.Get rid of the enclosing
[]
forprePopulate
becausejson_encode
is already doing that for you:您的 prePopulate 变量是一个包含对象数组的数组,但您只想它是一个对象数组。
您可以去掉 PHP 块之前和之后的 [ 和 ] 括号,或者在 PHP 块中回显此内容:
array_pop(json_decode($responses))
Your prePopulate variable is an array containing an array of objects, but you just want it to be an array of objects.
You can either take off the [ and ] brackets before and after the PHP block, or echo this in your PHP block:
array_pop(json_decode($responses))