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

提交表单后发起Pure Javascript Ajax请求的实现咨询

实现带Ajax提交的联系表单(同一页显示结果)

没问题,我来一步步帮你搞定这个需求。咱们核心要做的就是阻止表单默认跳转、前端先做基础验证、用Ajax发数据到send.php,最后把结果展示在当前页面。下面是具体实现步骤和代码:

1. 页面准备:添加结果展示容器

首先在你的联系表单旁边,加一个用来显示提交结果的元素,方便用户看到反馈:

<form id="contact-form" action="send.php" method="POST">
  <!-- 你的表单字段:根据需求添加姓名、邮箱、消息等 -->
  <input type="text" id="name" name="name" placeholder="姓名" required>
  <input type="email" id="email" name="email" placeholder="邮箱" required>
  <textarea id="message" name="message" placeholder="留言内容" required></textarea>
  <button type="submit">提交留言</button>
</form>
<!-- 专门用来显示提交结果的容器 -->
<div id="result-container"></div>

2. js.js 核心代码实现

在js.js里,我们要监听表单的提交事件,完成几个关键动作,代码里我都加了注释,方便你理解:

// 获取页面上的表单和结果容器元素
const contactForm = document.getElementById('contact-form');
const resultContainer = document.getElementById('result-container');

// 监听表单的提交事件
contactForm.addEventListener('submit', async (e) => {
  // 第一步:阻止表单默认的跳转行为(这是实现同一页显示结果的核心!)
  e.preventDefault();

  // 第二步:前端先做字段完整性验证,减少无效请求
  const name = document.getElementById('name').value.trim();
  const email = document.getElementById('email').value.trim();
  const message = document.getElementById('message').value.trim();

  // 检查必填字段是否为空
  if (!name || !email || !message) {
    showResult('请填写所有必填字段哦!', 'red');
    return;
  }

  // 简单验证邮箱格式(可选但推荐,避免用户输入无效邮箱)
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email)) {
    showResult('请输入有效的邮箱地址!', 'red');
    return;
  }

  // 第三步:准备表单数据,发起Ajax请求
  const formData = new FormData(contactForm); // 自动封装所有表单字段,不用手动拼接

  try {
    // 用Fetch API发起POST请求(现代浏览器都支持,语法比XMLHttpRequest更简洁)
    const response = await fetch('send.php', {
      method: 'POST',
      body: formData
    });

    // 接收send.php返回的结果(如果你的send.php返回JSON,就改成response.json())
    const responseText = await response.text();
    
    // 根据请求是否成功,显示对应结果
    if (response.ok) {
      showResult(responseText, 'green');
      contactForm.reset(); // 可选:提交成功后自动清空表单
    } else {
      showResult(responseText, 'red');
    }
  } catch (error) {
    // 处理网络异常、请求超时等意外情况
    showResult('提交失败,请稍后重试!', 'red');
    console.error('请求出错了:', error); // 控制台打印错误,方便你调试
  }
});

// 封装一个显示结果的小函数,避免重复写样式代码
function showResult(text, color) {
  resultContainer.textContent = text;
  resultContainer.style.color = color;
}

3. 配合send.php的注意事项

你的send.php已经有PHPMailer和校验逻辑,只需要调整返回结果的方式:

  • 当邮件发送成功、校验通过时,直接输出成功提示(比如echo '消息发送成功!我们会尽快回复你~';),默认HTTP状态码是200,前端会识别为成功。
  • 当校验失败、邮件发送失败时,输出错误提示(比如echo '抱歉,消息发送失败,请检查后重试!';),可以用http_response_code(400);设置错误状态码,方便前端判断。

另外,别忘了处理JS禁用的场景:send.php处理完后,重定向到index.php并携带状态参数,比如:

// send.php处理完业务逻辑后
if ($sendSuccess) {
  header('Location: index.php?status=success');
} else {
  header('Location: index.php?status=error');
}
exit;

然后在index.php里读取参数,给禁用JS的用户显示结果:

<?php if (isset($_GET['status'])): ?>
  <div id="result-container" style="color: <?= $_GET['status'] === 'success' ? 'green' : 'red' ?>;">
    <?= $_GET['status'] === 'success' ? '消息发送成功!' : '消息发送失败,请重试!' ?>
  </div>
<?php endif; ?>

这样不管用户的浏览器是否启用JS,都能正常看到提交结果,完美覆盖两种场景~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:56:28