简体   繁体   English

JSON中位置43的意外令牌

[英]Unexpected token in JSON at position 43

Im trying to Fetch Data From a PHP Server Running MySQL. 我试图从运行MySQL的PHP​​服务器中获取数据。 In my angular controller I do $http.get("dbconnection.php") 在我的角度控制器中,我执行$http.get("dbconnection.php")

In my dbconnection.php I have this code which just Selects everything from the database and sends it back. 在我的dbconnection.php中,我有这段代码,该代码仅从数据库中选择所有内容并将其发送回去。

$conn = new mysqli......

$result = $conn->query("SELECT * FROM ...");

$outp = "";

while ($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    if ($outp != "") {
        $outp .= ",";
    }
    $outp .= '{"id":"' . $rs["id"] . '",';
    $outp .= '"name":"' . $rs["name"] . '",';
    $outp .= '"price":"' . $rs["price"] . '"}';
    $outp .= '"created":"' . $rs["created"] . '"}';
    $outp .= '"img":"' . $rs["img"] . '"}';
}
$outp = '{"records":[' . $outp . ']}';
$conn->close();

echo $outp;

When I visit my site to see take a look at the Data under 当我访问我的网站以查看下面的数据时

Network Tab > XHR > dbconnection.php > Preview

I see the data but its weird formatted. 我看到了数据,但格式很奇怪。

See picture of weird formatted json 查看奇怪格式的json图片

I think thats the reason for why I get the 我认为这就是为什么我得到

Unexpected token in JSON at position 43 ERROR when I am trying to fetch the data. 当我尝试获取数据时Unexpected token in JSON at position 43错误。

To got well formatted JSON outputs, use json_encode function. 要获得格式良好的JSON输出,请使用json_encode函数。

In your case : 在您的情况下:

$conn = new mysqli......

$result = $conn->query("SELECT * FROM ...");
$json = ["records" => []];

while ($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    $json["records"][] = $rs;
}
$conn->close();

echo json_encode($json);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM