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

如何将jQuery POST请求代码转换为纯JavaScript的Fetch实现?

用Fetch API实现替代jQuery的POST请求

当然可以用Fetch API实现这个POST请求!我们可以基于你已经写好的GET请求逻辑,把原有的jQuery Ajax代码转换成纯JavaScript的Fetch版本,完美实现相同的功能。

完整实现代码

// 第一步:获取表单数据(和原jQuery代码一致)
let name = document.getElementById("Name").value; 
let code = document.getElementById("Code").value; 
let type = document.getElementById("ProductTypeId").value; 

// 构造要发送的请求数据(这里以JSON格式为例,若后端需要表单数据可看下方说明)
const postData = { name, code, type };

// 第二步:发起Fetch POST请求
fetch("/Home/jQueryAddComment", {
    method: "POST", // 指定POST请求方法,对应jQuery的type: "POST"
    headers: {
        "Content-Type": "application/json", // 告知服务器请求体为JSON格式
    },
    body: JSON.stringify(postData) // 将JS对象转为JSON字符串,对应jQuery的data: json
})
.then(function (response) {
    // 复用你GET请求中的重定向与错误页处理逻辑
    if (response.redirected && response.url.indexOf("/Error") > 0) {
        return response.text().then(function () {
            window.location.href = response.url;
        });
    }

    // 检查响应状态是否正常(2xx状态码)
    if (!response.ok) {
        throw new Error(`请求失败!状态码:${response.status}`);
    }

    // 获取返回的HTML文本,对应jQuery的dataType: "html"
    return response.text();
})
.then(function (html) {
    // 成功后执行的逻辑:弹窗提示 + 更新页面内容
    alert(html);
    document.querySelector('.CommentSection').innerHTML = html; // 替代jQuery的$('.CommentSection').html(data)
})
.catch(function (err) {
    console.log('Fetch Error', err);
});

关键细节说明

  • 请求数据格式调整:如果你的后端期望接收表单格式数据(而非JSON),可以改用FormData来构造请求体,无需手动设置Content-Type:
    const formData = new FormData();
    formData.append("name", name);
    formData.append("code", code);
    formData.append("type", type);
    
    // 此时fetch的配置只需修改body:
    fetch("/Home/jQueryAddComment", {
        method: "POST",
        body: formData
    })
    // ...后续逻辑不变
    
  • 响应处理:我们保留了你原GET请求中的重定向检测逻辑,同时新增了HTTP状态码检查,避免在请求失败时继续执行后续DOM更新操作。
  • DOM操作替代:用原生JS的document.querySelector('.CommentSection').innerHTML替代jQuery的$('.CommentSection').html(),实现完全相同的页面更新效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 11:42:37