JQuery Ajax接收JSON返回值无法访问内部数据求助
无法访问AJAX返回的JSON数据问题解决
问题描述
我写了一段jQuery的AJAX代码提交表单数据,对应的PHP处理逻辑执行数据库更新和查询,但Chrome控制台里收到的响应是两个拼接的JSON字符串,没法访问里面的数据:
前端JS代码:
$(function(){ var url = 'template/traitComTest.php'; window.onload = function(e) { $.ajax({ type: "POST", url: url, data: $( ".formCom").serializeArray(), success: function(response){ console.log(response); // 这里无法访问response.result或response.result1 } }); } });
后端PHP代码:
if (isset($_REQUEST)) { $adresse = $_POST['adresse']; $com = $_POST['commentaire']; $sql = $bdd->prepare('UPDATE tempSelector_template SET commentaire= :com WHERE exemple = :exem '); $sql->execute(array( ":com" => $com, ":exem" => $adresse )); $myData1 = array('result' => $sql); echo json_encode($myData1); $sql->closeCursor(); $sqlSelect = $bdd->prepare("SELECT commentaire FROM tempSelector_template WHERE exemple= :exemp"); $sqlSelect->execute(array( ":exemp" => $adresse )); $myData = array('result1' => $sqlSelect); echo json_encode($myData); }
收到的响应内容:
{"result":{"queryString":"UPDATE tempSelector_template SET commentaire= :com WHERE exemple = :exem "}}{"result1":{"queryString":"SELECT commentaire FROM tempSelector_template WHERE exemple= :exemp"}}
问题根源
你的PHP代码犯了两个关键错误:
- 连续输出两个独立JSON字符串:标准JSON要求整个响应是单一的JSON值(对象或数组),而你输出的是
{...}{...}这种拼接格式,属于无效JSON,jQuery无法自动解析成可访问的JS对象。 - 序列化了错误的对象:你直接把PDO的
PDOStatement对象($sql和$sqlSelect)放进数组序列化,这只会得到statement的内部属性(比如你看到的queryString),而不是实际的数据库操作结果或查询数据。
解决方案
1. 修复后端PHP代码
把两个操作的结果合并到一个数组,只执行一次json_encode和echo,同时正确获取数据库操作的有效结果:
// 更严谨的参数校验,避免Undefined Index错误 if (isset($_POST['adresse']) && isset($_POST['commentaire'])) { $adresse = $_POST['adresse']; $com = $_POST['commentaire']; // 执行更新操作,获取影响行数 $sql = $bdd->prepare('UPDATE tempSelector_template SET commentaire= :com WHERE exemple = :exem '); $updateSuccess = $sql->execute(array( ":com" => $com, ":exem" => $adresse )); $affectedRows = $sql->rowCount(); // 获取更新影响的行数 $sql->closeCursor(); // 执行查询操作,获取实际的评论数据 $sqlSelect = $bdd->prepare("SELECT commentaire FROM tempSelector_template WHERE exemple= :exemp"); $sqlSelect->execute(array( ":exemp" => $adresse )); $commentData = $sqlSelect->fetch(PDO::FETCH_ASSOC); // 获取查询结果 $sqlSelect->closeCursor(); // 合并所有结果到一个数组 $responseData = array( 'update_success' => $updateSuccess, 'affected_rows' => $affectedRows, 'latest_comment' => $commentData['commentaire'] ?? null // 处理查询结果为空的情况 ); // 设置正确的响应头,确保浏览器识别为JSON header('Content-Type: application/json'); echo json_encode($responseData); exit; // 终止脚本,避免后续多余输出 } else { // 参数缺失时返回错误响应 header('Content-Type: application/json'); echo json_encode(array('error' => '缺少必要参数')); exit; }
2. 优化前端AJAX代码
在请求中指定dataType: 'json'让jQuery自动解析响应,同时添加错误处理逻辑:
$(function(){ var url = 'template/traitComTest.php'; // 注意:$(function(){})本身就是DOM加载完成的回调,无需嵌套window.onload $(window).on('load', function(e) { $.ajax({ type: "POST", url: url, data: $( ".formCom").serializeArray(), dataType: 'json', // 告诉jQuery预期返回JSON格式 success: function(response){ console.log('更新是否成功:', response.update_success); console.log('影响行数:', response.affected_rows); console.log('最新评论内容:', response.latest_comment); // 现在可以正常访问所有响应属性了 }, error: function(xhr, status, error){ console.error('AJAX请求出错:', error); console.error('错误响应内容:', xhr.responseText); } }); }); });
额外提示
- 永远不要直接序列化PDOStatement对象,要用
rowCount()获取更新/删除操作的影响行数,用fetch()/fetchAll()获取查询结果。 - 输出JSON前一定要设置
Content-Type: application/json响应头,确保浏览器正确识别响应类型。 - 对用户传入的参数做校验,避免因参数缺失导致的运行时错误。
内容的提问来源于stack exchange,提问作者IZAD
相关产品推荐
相关产品推荐

