在Javascript中读取PHP返回的JSON

时间:2015-11-24 08:42:31

标签: javascript php jquery arrays json

我想从数据库中选择一些内容并将其返回给javascript。数据库返回了几行。如果我打印出来的话,我用JSON尝试了这个并得到了结果。但是如果我想转换JSON字符串,则总会出现以下错误消息。 (在JSON.parse)所以,我假设在填充数组时可能出错了?先谢谢你们!

使用Javascript:

$.ajax({
  url: "./select_firsttracks.php",
  type: "post",
  success: function(resultset) {
    $("#erroroutput").html(resultset);

    var arr = JSON.parse("{" + resultset + "}"); // --> "Uncaught SyntaxError: Unexpected token {"            
  },
  error: function(output) {
    $("#erroroutput").html("fatal error while fetching tracks from db: " + output);
  }
});

PHP:

$storage = array();
while($row = $result->fetch_array())
{
    $storage[] = 
        array
        (
            "id" => $row["id"],
            "trackname" => $row["trackname"],
            "artist" => $row["artist"],
            "genre" => $row["genre"],
            "url" => $row["url"],
            "musicovideo" => $row["musicovideo"]
        );

    echo json_encode($storage);
}

控制台上的输出:

[{"id":"1","trackname":"yes","artist":"Lady Gaga","genre":"Pop","url":"ftp:\/development","musicovideo":"1"}][{"id":"1","trackname":"yes","artist":"Lady Gaga","genre":"Pop","url":"ftp:\/development","musicovideo":"1"},{"id":"2","trackname":"no","artist":"Prinz Pi","genre":"Rap","url":"ftp:\/development","musicovideo":"1"}]

3 个答案:

答案 0 :(得分:4)

之后回显json
$storage = array();
while($row = $result->fetch_array())
{
    $storage[] = 
        array
        (
            "id" => $row["id"],
            "trackname" => $row["trackname"],
            "artist" => $row["artist"],
            "genre" => $row["genre"],
            "url" => $row["url"],
            "musicovideo" => $row["musicovideo"]
        );


}
echo json_encode($storage);

并改变:

 var arr = JSON.parse(resultset);

答案 1 :(得分:2)

您在收到的JSON前后添加花括号,在这里:

var arr = JSON.parse("{" + resultset + "}");

Phps json_encode自己返回完全有效的JSON。尝试不添加大括号:

var arr = JSON.parse(resultset);

答案 2 :(得分:1)

生成的json字符串无效,您可以使用jsonlint

进行检查

将你的php代码修改为循环外的echo

while($row = $result->fetch_array())
{
    $storage[] = 
        array
        (
            "id" => $row["id"],
            "trackname" => $row["trackname"],
            "artist" => $row["artist"],
            "genre" => $row["genre"],
            "url" => $row["url"],
            "musicovideo" => $row["musicovideo"]
        );


}
echo json_encode($storage);

在javascript中只使用输出作为javascript对象

success: function(resultset) {
    console.log(resultset)
    resultset.each(function(index,element){ console.log(index,element )})
  },