dqwp81696 2011-03-31 16:15
浏览 8
已采纳

从php json_encode显示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 :))

  • 写回答

2条回答 默认 最新

  • dongyonglie5132 2011-03-31 16:20
    关注

    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 [] for prePopulate because json_encode is already doing that for you:

    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);
                ?>,
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用