gpt4 book ai didi

javascript - 在 Javascript 中读取 PHP 返回的 JSON

转载 作者:行者123 更新时间:2023-12-01 02:28:14 25 4
gpt4 key购买 nike

我想从数据库中选择一些内容并将其返回给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"}]

最佳答案

稍后回显 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);

关于javascript - 在 Javascript 中读取 PHP 返回的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33888952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com