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

使用AJAX获取Outing表数据并在HTML展示的问题排查

问题排查与修复方案

问题1:AJAX请求时页面跳转到outing_details.php

原因分析

AJAX本身是异步无刷新请求,出现页面跳转大概率是页面中存在触发默认跳转行为的元素(比如表单提交按钮、直接指向outing_details.php的<a>标签),且没有阻止这些元素的默认事件。例如:

  • 按钮是表单提交按钮,点击时先触发AJAX,再执行表单提交跳转;
  • 存在<a href="outing_details.php">标签,点击后直接触发页面跳转。

修复步骤

  1. 检查并处理表单提交:
    如果页面有表单,给表单添加阻止默认提交的逻辑:
    $('form').submit(function(e) {
      e.preventDefault(); // 阻止表单默认跳转行为
      // 执行数据上传等原有逻辑
    });
    
  2. 处理<a>标签跳转:
    要么修改<a>标签的href属性为javascript:void(0),要么在点击事件中阻止默认行为:
    $('a[href="outing_details.php"]').click(function(e) {
      e.preventDefault();
      getOutingDetails();
    });
    
  3. 确认页面中没有其他触发跳转的代码,确保只有AJAX异步请求逻辑。

问题2:数据未按预期在HTML中展示

原因分析

核心问题是AJAX没有正确解析PHP返回的JSON数据:

  • PHP端返回的是JSON格式字符串,但未设置正确的响应头,jQuery默认可能将其识别为普通字符串;
  • JS端未指定数据类型,导致data是字符串而非JSON对象,循环时outing.title等属性会变为undefined,无法渲染内容。

修复步骤

步骤1:优化PHP端,添加JSON响应头

在outing_details.php中,输出JSON前添加响应头,明确告知浏览器返回的是JSON数据:

header('Content-Type: application/json');
echo json_encode($outingData);

同时优化错误处理,确保数据库连接失败时也返回JSON格式错误信息:

if (!$conn) {
  header('Content-Type: application/json');
  echo json_encode(['error' => "Connection failed: " . mysqli_connect_error()]);
  exit;
}

步骤2:优化JS端,指定数据类型

在connectAjax.js的AJAX配置中添加dataType: 'json',强制jQuery将响应解析为JSON对象,同时增加空数据提示:

function getOutingDetails() {
  $.ajax({
    url: "outing_details.php",
    type: "GET",
    dataType: 'json', // 强制指定返回数据类型为JSON
    success: function(data) {
      $("#outingDetails").empty();
      // 空数据提示
      if(data.length === 0) {
        $("#outingDetails").append("<p>暂无出行记录</p>");
        return;
      }
      for (var i = 0; i < data.length; i++) {
        var outing = data[i];
        $("#outingDetails").append(
          `<p class='Outing_Title'>${outing.title}</p>` +
          `<p class='Outing_Place'>${outing.place}</p>` +
          `<p class='Outing_Date'>${outing.date}</p>` +
          "<hr>"
        );
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.error("Error retrieving outing details:", textStatus, errorThrown);
      $("#outingDetails").empty().append("<p>加载出行数据失败,请稍后重试</p>");
    }
  });
}

验证方法

打开浏览器开发者工具的网络面板,查看outing_details.php的响应:

  • 确认响应头包含Content-Type: application/json;
  • 确认响应内容是合法的JSON数组(如[{"title":"xxx","place":"xxx","date":"xxx"}])。

修改后的完整代码片段

优化后的outing_details.php

<?php
// Connect to your database
$servername = "ignore_this";
$username = "ignore_this";
$password = "ignore_this";
$dbname = "ignore_this";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
  header('Content-Type: application/json');
  echo json_encode(['error' => "Connection failed: " . mysqli_connect_error()]);
  exit;
}

$sql = "SELECT title, place, date FROM Outing";
$result = mysqli_query($conn, $sql);

$outingData = array();
if (mysqli_num_rows($result) > 0) {
  while ($row = mysqli_fetch_assoc($result)) {
    $outingData[] = $row;
  }
}

mysqli_close($conn);

header('Content-Type: application/json');
echo json_encode($outingData);
?>

优化后的connectAjax.js

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

function getOutingDetails() {
  $.ajax({
    url: "outing_details.php",
    type: "GET",
    dataType: 'json',
    success: function(data) {
      $("#outingDetails").empty();
      if(data.length === 0) {
        $("#outingDetails").append("<p>暂无出行记录</p>");
        return;
      }
      for (var i = 0; i < data.length; i++) {
        var outing = data[i];
        $("#outingDetails").append(
          `<p class='Outing_Title'>${outing.title}</p>` +
          `<p class='Outing_Place'>${outing.place}</p>` +
          `<p class='Outing_Date'>${outing.date}</p>` +
          "<hr>"
        );
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.error("Error retrieving outing details:", textStatus, errorThrown);
      $("#outingDetails").empty().append("<p>加载出行数据失败,请稍后重试</p>");
    }
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 21:04:59