You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过$.ajax和JSON实现PHP向JavaScript传值?解析报错求助

解决PHP通过AJAX传递JSON数据时的"Unexpected end of JSON input"错误

我尝试用PHP从tbl_user_posts表获取帖子数据,通过$.AJAX传递给JavaScript解析,但控制台报错Unexpected end of JSON input,错误出在JSON.parse(response)行。相关代码如下:

原PHP代码

//This is to retrieve all the posts inside the database, which will then be displayed using Javascript.
function retrieve_post($connection) {
    $sql2 = "SELECT * FROM tbl_user_posts";
    $result = mysqli_query($connection, $sql2);
    echo json_encode($result);
    //$data = array();
    //while ($row = mysqli_fetch_assoc($result)) {
    //    $data[] = $row;
    //    echo json_encode($data);
    //}
}

原JavaScript代码

function displayPosts(){
  $.ajax({
    type: "POST",
    url: "Main_Page.php",
    success: function(response) {
      JSON.stringify(response);
      var data = JSON.parse(response);
      for (var i = 0; i < data.length; i++) {
        var row = data[i];
        var name = row.name;
        var user_post = row.user_post;
        console.log(name, user_post);
      }
    }
  });
}

$(document).ready(function() {
  displayPosts();
});

报错信息

Unexpected end of JSON input
at JSON.parse ()
at Object.success (Main_Page.js:77:23)

原HTML代码

<div class="user-post">
    Create post:<br>
    <form id="form" method="POST">
        <textarea id = "create_post" name="create_post" rows="10" cols = "50"></textarea>
        <input type="submit" class="post-button" value="PostButton" onclick = submit_post()>
    </form>
</div>
<div class="posts" id="posted">
    <div class="post">
        <h3 id="existing_posts"><img src="default-pic.png" class="profile-pic" alt="Default Picture" width="50" height="50">Posts</h3>
        <p>This is an example of a post. It will need to be boxed and made so that the name of the user goes above
            the name of the likes and dislikes of the posts are to the left of the post and that the reply and report
            functionalities are at the bottom right of the posts. It will also need a box around it to show where the post starts and ends.</p>
        <div class="options">
            <a href="">Like</a>
            <a href="">Comment</a>
            <a href="" class="report">Report</a>
        </div>
    </div>
</div>

错误原因

  • PHP端核心问题:直接对mysqli_query返回的结果集对象执行json_encode无效,该对象无法被序列化为合法JSON;注释代码中循环内多次echo json_encode会输出多个JSON片段,导致返回内容不是单一合法JSON结构。
  • JS端冗余操作:未指定dataType: 'json'时jQuery不会自动解析JSON,且JSON.stringify(response)是多余操作,会干扰后续解析逻辑。
  • 潜在输出污染:如果Main_Page.php除了JSON输出外还包含HTML或其他echo内容,会破坏返回的纯JSON结构。

修正后的代码

修正后的PHP代码

// 获取所有帖子数据并返回JSON
function retrieve_post($connection) {
    // 设置响应头为JSON类型,明确告知前端数据格式
    header('Content-Type: application/json');
    
    $sql2 = "SELECT * FROM tbl_user_posts";
    $result = mysqli_query($connection, $sql2);

    // 检查查询是否成功
    if (!$result) {
        echo json_encode(array('error' => mysqli_error($connection)));
        exit;
    }
    
    // 将结果集转换为关联数组
    $data = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }
    
    // 一次性输出JSON并终止脚本,避免其他内容污染输出
    echo json_encode($data);
    exit;
}

修正后的JavaScript代码

function displayPosts(){
  $.ajax({
    type: "POST",
    url: "Main_Page.php",
    // 指定返回数据类型为JSON,jQuery会自动完成解析
    dataType: "json",
    success: function(data) {
      // 直接使用已解析的data数组
      for (var i = 0; i < data.length; i++) {
        var row = data[i];
        var name = row.name;
        var user_post = row.user_post;
        console.log(name, user_post);
      }
    },
    // 增加错误回调,方便调试请求异常
    error: function(xhr, status, error) {
      console.error("AJAX请求错误:", status, error);
      console.error("返回内容:", xhr.responseText);
    }
  });
}

$(document).ready(function() {
  displayPosts();
});

额外注意事项

  • 确保Main_Page.php中只有retrieve_post函数的JSON输出,无其他HTML、echo或空白字符输出,否则会破坏JSON结构。
  • 验证数据库连接有效性,避免因连接失败导致无数据返回。

内容的提问来源于stack exchange,提问作者Jeremy Panthier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 08:27:10