You need to enable JavaScript to run this app. JavaScript中如何将现有AJAX POST请求改造为异步执行?
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何将现有AJAX POST请求改造为异步执行?

现有代码问题说明

XMLHttpRequest.open 方法的第三个参数默认值为 true,本身就是异步执行模式,只有手动设置为 false 时才是同步阻塞模式。你当前的写法已经是异步逻辑,主要存在以下可优化问题:

  • onreadystatechange 用普通函数作为回调,this 指向的是XHR实例而非外层组件实例,会导致修改this.submitStatus、this.isDisabled不生效
  • 提交成功提示、表单重置逻辑写在了ajax.send()之后,异步模式下send执行后不会等后端返回就会直接执行后续代码,导致不管请求结果如何都会提前清空表单、提示发送成功
  • 存在拼写错误:isDisbabled 应为 isDisabled

方案1:修复现有XHR异步逻辑

submitForm(e) {
  console.log(e);
  e.preventDefault();
  // 先禁止重复提交,提交中状态提示
  this.isDisabled = true;
  this.submitStatus = '正在提交中...';

  const formData = new FormData();
  formData.append('user_name', this.user_name);
  formData.append('user_email', this.user_email);
  formData.append('user_message', this.user_message);

  const ajax = new XMLHttpRequest();
  // 第三个参数默认true,为异步执行模式
  ajax.open('POST', this.url);

  // 用箭头函数绑定外层this,避免指向XHR实例
  ajax.onreadystatechange = () => {
    if(ajax.readyState === 4 && ajax.status === 200) {
      if (ajax.responseText === "success") {
        this.submitStatus = `感谢您 ${this.user_name},您的消息已提交成功`;
        // 请求成功后再重置表单
        this.user_name = "";
        this.user_email = "";
        this.user_message = "";
      } else {
        this.submitStatus = ajax.responseText;
        // 请求失败恢复提交按钮
        this.isDisabled = false;
      }
    }
  }
  // 新增网络异常处理
  ajax.onerror = () => {
    this.submitStatus = '网络异常,请稍后重试';
    this.isDisabled = false;
  }

  ajax.send(formData);
}

方案2:封装为Promise配合async/await写法(符合现代异步代码习惯)

// 先封装通用POST表单请求方法
postForm(url, formData) {
  return new Promise((resolve, reject) => {
    const ajax = new XMLHttpRequest();
    ajax.open('POST', url);
    ajax.onreadystatechange = () => {
      if(ajax.readyState === 4) {
        if(ajax.status === 200) {
          resolve(ajax.responseText);
        } else {
          reject(new Error(`请求失败,状态码:${ajax.status}`));
        }
      }
    };
    ajax.onerror = () => reject(new Error('网络异常'));
    ajax.send(formData);
  })
}

// submitForm改为async异步函数
async submitForm(e) {
  console.log(e);
  e.preventDefault();
  this.isDisabled = true;
  this.submitStatus = '正在提交中...';

  const formData = new FormData();
  formData.append('user_name', this.user_name);
  formData.append('user_email', this.user_email);
  formData.append('user_message', this.user_message);

  try {
    const res = await this.postForm(this.url, formData);
    if(res === 'success') {
      this.submitStatus = `感谢您 ${this.user_name},您的消息已提交成功`;
      this.user_name = "";
      this.user_email = "";
      this.user_message = "";
    } else {
      this.submitStatus = res;
      this.isDisabled = false;
    }
  } catch (err) {
    this.submitStatus = err.message;
    this.isDisabled = false;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 02:06:04