[英]I know why I am getting unexpected { token but I don't know how to fix it when my php needs to send collection of datas to javascript
我正在使用这个 javascript 获取代码从 php 获取数据
async sendRequest(selectValue=this.selectValue){
const fetchResponse = await fetch('/server/getLastWords.php?select='+selectValue);
const fetchJSON = await fetchResponse.json();
await console.log(fetchJSON);
}
这是与 MYSQL 通信并将数据发送到 javascript 的 php 代码
<?php
header('Content-Type: application/json');
include 'db/db_connection.php';
$mysqli = new mysqli('localhost','root','','worddb');
if(connectDB($mysqli)){
$mysqliQuery = "SELECT * FROM wordlist ORDER BY wordIndex DESC LIMIT ?";
$stmt = $mysqli->stmt_init();
if(!$stmt->prepare($mysqliQuery)){
print "Failed to prepare statement\n";
}else{
$stmt->bind_param("i", $_GET['select']);
$stmt->execute();
$result = $stmt->get_result();
$resultJSON;
foreach($result as $resultArray){
$resultJSON = json_encode($resultArray);
echo $resultJSON;
}
}
}
?>
这个 php 返回
{"wordIndex":94,"english":"seemingly","korean":"\uc678\uacac\uc0c1\uc73c\ub85c,
\uac89\ubcf4\uae30\uc5d0\ub294","swedish":"till synes","synonyms":"apparently","example":"Seemingly,
he borrowed the money from the bank"}
{"wordIndex":93,"english":"evade","korean":"\ud53c\ud558\ub2e4,
\ud68c\ud53c\ud558\ub2e4","swedish":"undvika","synonyms":"elude, evoid","example":"He is using the
same tactics of distract and evade as the Chancellor used during his speech"}
{"wordIndex":92,"english":"eclipse","korean":"\uac00\ub9ac\ub2e4, \ube5b\uc744
\uc783\uc74c","swedish":"f\u00f6rm\u00f6rka","synonyms":"blocking, beating","example":"Her work was
in eclipse for most of the 20th century"}
{"wordIndex":91,"english":"impede","korean":"\uc9c0\uc5f0\uc2dc\ud0a4\ub2e4",
"swedish":"f\u00f6rhindra","synonyms":"delay, hinder","example":"This will impede learning,
essentially causing more problems than solutions"}
{"wordIndex":90,"english":"exposure","korean":"\uc704\ud5d8\uc5d0 \ub178\ucd9c,
\ud3ed\ub85c","swedish":"exponering","synonyms":"subjection, uncovering","example":"God knows you
probably saved my life, at least from exposure or pneumonia"}
我知道它显示了意外的令牌 { 因为 php 正在返回多个 json 对象,因为
当我只回显一个 json 对象时,它工作正常。
$resultJSON;
foreach($result as $resultArray){
$resultJSON =json_encode($resultArray);
}
echo($resultJSON);
但我的 php 需要发送所有项目,但我不知道该怎么做,因为控制台显示了意外的令牌 {}
我在发布我的问题之前阅读了这篇文章为什么我会收到意外的“}”? 但是这篇文章中的解决方案是添加分号,但我的代码中有分号..
这里出错了:
$resultJSON;
foreach($result as $resultArray){
$resultJSON = json_encode($resultArray);
echo $resultJSON;
}
你输出:
echo json1;
echo json2;
echo json3;
但是,在客户端,输出被收集并视为一个 json。 所以 javascript 将与json1json2json3
一起json1json2json3
。 这不是有效的 json。
如果您不必做任何其他事情,则将结果发回
echo json_encode($result);
会做。
将结果转换为数组:
$resultJSON = array();
foreach($result as $resultArray){
$resultJSON[] = $resultArray;
}
然后输出数组:
echo json_encode($resultJSON);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.