fetch_array(MYSQLI_ASSOC)) { if ($o-6ren">
gpt4 book ai didi

javascript - JSON 中位置 39 处出现意外标记

转载 作者:行者123 更新时间:2023-11-28 04:51:55 25 4
gpt4 key购买 nike

我有一个用于字典 Web 应用程序的 php api,

$outp = "";

while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "") {$outp .= ",";}
$outp .= '{"WORD":"' . $rs["word"] . '",';
$outp .= '"MEANING":"' . $rs["definition"] . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();

echo($outp);

}
else
{


}
?>

在 angularJS 端,解析函数如下:

$scope.counter = function() {
console.log(JSON.stringify(response));

if($scope.name) {
$http.get("http://localhost/dictionary/API/search.php?qr="+$scope.name)
.then(function (response) {
console.log(JSON.stringify(response.records));
if(response.data.records=="") {
queryRes = response.data.records ;
$scope.word = "";
$scope.meaning = ""
} else {

queryRes = response.data.records ;
$scope.word = queryRes[0].WORD;
$scope.meaning = queryRes[0].MEANING;
}

});

}

}

当 php api 像这样返回单元素数组 JSON 时没有错误

{"records":[{"WORD":"Net","MEANING":"വല"}]}

但是当 php 返回多个元素的数组时,例如 ,

{"records":[{"WORD": "End","MEANING": "അറുതി
"},{"WORD": "End","MEANING": "അവസാനം
"},{"WORD": "End","MEANING": "അതിര്‌
"},{"WORD": "End","MEANING": "സീമ
"},{"WORD": "End","MEANING": "പരിസമാപ്‌തി
"},{"WORD": "End","MEANING": "അവസാനഘട്ടം
"},{"WORD": "End","MEANING": "മരണം
"}]}

出现这样的错误

Unexpected token in JSON at position 39 at JSON.parse (<anonymous>)

我认为 JSON 对象操作存在一些问题。

最佳答案

不要通过字符串连接构建 JSON;使用json_encode .

$records = [];

while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
$records[] = [
'WORD' => $rs["word"],
'MEANING' => $rs["definition"],
];
}
$conn->close();

echo json_encode(['records' => $records]);

关于javascript - JSON 中位置 39 处出现意外标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42850657/

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