如何将这段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
相关产品推荐
相关产品推荐

