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条)

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试