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

相关推荐 更多相似问题