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

如何将这段jQuery Ajax代码转换为原生JavaScript Fetch?

jQuery Ajax 转原生JavaScript Fetch 完整实现

转换后的完整代码

// 替换原ajaxCall变量,Fetch返回Promise
const ajaxCall = fetch('data.php', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: `ajax=1&do=check&lista=${encodeURIComponent(leray[chenille])}`,
  cache: 'no-store' // 对应原cache: false,确保不缓存
})
.then(response => {
  // 检查HTTP响应状态是否成功
  if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status}`);
  }
  // 对应原dataType: "json",解析JSON响应
  return response.json();
})
.then(oreen => {
  // 原success回调里的逻辑直接迁移过来
  switch (oreen.enviando) {
    case -1:
      chenille++;
      document.getElementById('div1').insertAdjacentHTML('beforeend', `${oreen.cat}<br />`);
      updateProgress(chenille, leray.length);
      tvmit_wrongUp();
      break;

    case 1:
      chenille++;
      document.getElementById('div1').insertAdjacentHTML('beforeend', `${oreen.dog}<br />`);
      updateProgress(chenille, leray.length);
      tvmit_wrongUp();
      break;

    case 2:
      chenille++;
      document.getElementById('div2').insertAdjacentHTML('beforeend', `${oreen.sky}<br />`);
      nieva++;
      updateProgress(chenille, leray.length);
      tvmit_dieUp();
      break;

    case 3:
      chenille++;
      document.getElementById('div3').insertAdjacentHTML('beforeend', `${oreen.water}<br />`);
      tvmit_liveUp();
      updateProgress(chenille, leray.length);
      break;
  }

  OKTY(leray, chenille, aarsh, nieva);
})
.catch(error => {
  // 处理网络错误或HTTP错误
  console.error('请求出错:', error);
});

return true;

关键转换点说明

  • 请求方法与URL:直接将原代码的url和type对应到Fetch的第一个参数和options.method配置项
  • 请求体与Content-Type:原jQuery的表单格式数据直接作为body内容,同时设置Content-Type为application/x-www-form-urlencoded,确保后端能正确解析参数
  • JSON解析:原dataType: "json"需要手动调用response.json()方法解析响应内容
  • 缓存控制:用cache: 'no-store'完全禁止缓存,对应原代码的cache: false
  • DOM操作替换:把jQuery的$("#divX").append()替换为原生document.getElementById('divX').insertAdjacentHTML(),实现相同的DOM追加效果
  • 错误处理:Fetch不会自动抛出404、500这类HTTP错误,需要手动检查response.ok状态并抛出异常,再通过.catch()统一处理网络或请求错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 16:31:33