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

jQuery转原生JS:如何用XHR/Fetch以POST发送FormData?

解决方案:将jQuery的POST请求转为原生JS(模拟urlencoded格式)

你的$.post默认会把传入的对象序列化为**application/x-www-form-urlencoded**格式的键值对(比如id=xxx&product_id=xxx),而你之前用JSON或FormData的方式都不符合这个格式,以下是正确的原生实现:


1. 使用XMLHttpRequest实现

let xhr = new XMLHttpRequest();
xhr.open("POST", "/product/getList", true);
// 手动设置Content-Type(也可省略,发送URLSearchParams时浏览器会自动设置)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

// 将参数转为urlencoded格式
const params = new URLSearchParams({
    id: id,
    product_id: product_id.value
});

xhr.send(params);

xhr.onload = function() {
    let data = JSON.parse(this.responseText);
    console.log(data);
};

2. 使用Fetch API实现

fetch("/product/getList", {
    method: "POST",
    // 发送URLSearchParams时,浏览器会自动设置正确的Content-Type,无需手动指定
    body: new URLSearchParams({
        id: id,
        product_id: product_id.value
    })
}).then(response => response.json())
  .then(data => console.log(data));

为什么你之前的尝试不对?

  • 用JSON.stringify发送的是application/json格式,和$.post的默认格式完全不同;
  • 直接使用FormData时,浏览器会默认把请求头设为multipart/form-data(即使手动改x-www-form-urlencoded也不会变成普通键值对格式),这和$.post的application/x-www-form-urlencoded不是同一种格式,后端可能无法正确解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 23:35:23