【问题标题】:JSON parse error on line 1 expecting Expecting '{', '['第 1 行的 JSON 解析错误,期望期望 '{', '['
【发布时间】:2025-11-26 07:25:01
【问题描述】:

我这几天一直在尝试解析我的数据,但仍然不知道如何从使用 json_encode 编码的 PHP 数组中获取结果。我是 JQuery 新手。

这不起作用:

$.post('coordinate_array.php',{},function(data) {  //ERROR HERE EXPECTING SOMETHING??
 results = JSON.parse(data);
 for(i = 0;i < results.length;i++) {
  Paint(results[i].x, results[i].y);
 }
});

我正在从这个 php 文件中获取我的数据:

<?php
include 'db_conn.php';

header('Content-Type: application/json'); //not sure if i need this here??

$coordinate_sql = "SELECT x_coord, y_coord FROM coordinates";
$result = mysqli_query($conn,$coordinate_sql);

//see if query is good
if($result === false) {
    die(mysqli_error()); 
}

//array that will have number of desks in map area
    while($row = mysqli_fetch_assoc($result)){  

    //get desk array count      
    $desk[] = array('x' => $row['x_coord'], 
                                    'y' => $row['y_coord']);
} //end while loop
    echo json_encode($desk); //encode the array
?>

【问题讨论】:

  • 您没有显示任何内容,您需要执行以下操作:print(json_encode($desk));。此外,die(mysqli_error()) 不是 JSON,因此如果出现问题,它将是无效的 JSON……您的 PHP 文件中的其他地方也可能有错误,导致在 JSON 之前打印一些通知(或其他内容)。跨度>
  • 你的错误是?我唯一能看到的是你没有输出你的 json 数据。 json_encode() RETURNS 编码的字符串。它不做输出,所以你的脚本实际上是无用的,因为没有任何东西可以输出到客户端。你需要echo json_encode($desk)
  • 我添加了回声,但屏幕上仍然没有任何内容。这是我向你们展示我的数组确实具有值的结果:[{"x":"20","y" :"20"},{"x":"30","y":"30"},{"x":"40","y":"40"},{"x":"50" ,"y":"50"}] ...我在 JQuery 中做错了什么??
  • @MarcB 这是我的错误:第 1 行解析错误:$.post('coordinate_a ^ Expecting '{', '['
  • 为什么要做JSON.parse,返回的数据是数组,不是要解析的字符串。

标签: javascript php jquery mysql json


【解决方案1】:

你不是echoing 你的 JSON 数据,所以 JS 调用请求的页面总是空的。 使用:

echo json_encode($desk);

在文件末尾。

【讨论】:

  • @mario 这个请求的结果是什么?你应该使用curl 之类的工具来调试它,如果不是浏览器中的“网络”选项卡。
最近更新 更多