You need to enable JavaScript to run this app. 如何将邮件订阅表单的jQuery Ajax代码转换为原生纯JavaScript实现?
优惠活动
大模型
产品
解决方案
定价
更多

如何将邮件订阅表单的jQuery Ajax代码转换为原生纯JavaScript实现?

原生JS重写邮件订阅表单提交逻辑

实现范围

完全对齐现有jQuery版本的#newsLetter-form表单提交全流程,包含:

  • 表单提交拦截、邮箱值获取
  • 向/subscribes/emailSubscribe接口POST提交CSRF令牌、邮箱字段
  • 成功/错误状态的提示展示、样式切换
  • 3秒延迟的提示自动隐藏、表单复位逻辑

完整可运行代码

// 初始化DOM元素引用
const subscribeForm = document.querySelector('#newsLetter-form');
const emailInput = document.querySelector('#emailId');
const responseTipEl = document.querySelector('#responseFromSub');
const successTipEl = document.querySelector('.sucsessMessage');

// 为提示元素添加默认样式,还原淡入淡出效果
successTipEl.style.transition = 'opacity 0.3s ease';
successTipEl.style.opacity = '0';

// 绑定表单提交监听
subscribeForm.addEventListener('submit', (event) => {
  // 阻止表单默认刷新行为
  event.preventDefault();
  const currentEmail = emailInput.value;
  console.log(currentEmail);

  // 构造和jQuery默认格式一致的表单提交数据
  const submitData = new URLSearchParams();
  submitData.append('_token', '{{ csrf_token() }}');
  submitData.append('email', currentEmail);

  // 发起原生POST请求
  fetch('/subscribes/emailSubscribe', {
    method: 'POST',
    headers: {
      'X-Requested-With': 'XMLHttpRequest'
    },
    body: submitData
  })
  .then(async (res) => {
    if (res.ok) {
      // 成功分支逻辑
      const resData = await res.json();
      console.log(resData);
      responseTipEl.textContent = "Registred!";
      responseTipEl.style.background = 'lightgreen';
      subscribeForm.style.display = 'none';
      successTipEl.style.opacity = '1';

      // 3秒后复位界面
      setTimeout(() => {
        successTipEl.style.opacity = '0';
        subscribeForm.style.display = 'flex';
      }, 3000);
    } else {
      // 错误分支逻辑
      const errData = await res.json();
      console.log(errData);
      // 对齐原代码的错误信息提取逻辑
      const rawErrMsg = errData.message;
      let extractedMsg = rawErrMsg.substring(rawErrMsg.indexOf('"title":'));
      extractedMsg = extractedMsg.split(':').pop();
      extractedMsg = extractedMsg.split(',')[0];
      extractedMsg = extractedMsg.replace(/"/g, '');
      console.log(extractedMsg);

      responseTipEl.textContent = extractedMsg;
      responseTipEl.style.background = 'red';
      subscribeForm.style.display = 'none';
      successTipEl.style.opacity = '1';

      // 3秒后复位界面
      setTimeout(() => {
        successTipEl.style.opacity = '0';
        subscribeForm.style.display = 'flex';
      }, 3000);
    }
  })
  .catch((err) => {
    console.log('请求异常:', err);
  });
});

关键逻辑对应说明

  • 事件绑定:原生addEventListener('submit')完全替代jQuery的.on('submit'),阻止默认提交的行为和原逻辑一致
  • 取值:输入框的.value属性对应jQuery的.val()方法,获取的邮箱值无差异
  • 数据提交:URLSearchParams构造的表单数据,和jQuery默认POST的编码格式完全一致,服务端可正常解析字段
  • 样式操作:直接修改元素的style属性,对应jQuery的.css()方法的效果
  • 文本设置:元素的textContent属性对应jQuery的.text()方法,无多余HTML渲染风险
  • 过渡效果:通过元素透明度过渡实现淡入淡出,替代jQuery内置的.fadeIn()/.fadeOut(),视觉体验一致

注意事项

  • 原代码中错误信息解析部分存在双引号转义错误,实现中已修正为可正常运行的提取逻辑
  • 请求中补充的X-Requested-With头,可兼容Laravel框架对Ajax请求的识别,避免服务端返回页面视图而非预期的JSON数据
  • 所有延迟逻辑的时间间隔和原代码保持一致,交互节奏无差异

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.11 07:57:01