如何格式化原生XHR的POST数据 使其格式与jQuery ajax请求一致
问题根源
你当前的问题出在XMLHttpRequest.send()方法的入参格式和你设置的Content-Type不匹配:
- 你设置的请求头是
application/x-www-form-urlencoded类型,该类型要求请求体必须是符合键=值&键2=值2规则的URL编码字符串 - 原生
send()方法不会自动序列化JS对象,你直接传入{'content': packgJSON}对象时,浏览器会自动调用对象的toString()方法,得到无意义的[object Object]字符串,因此后端无法解析到正确的参数 - jQuery的
$.ajax默认会自动把传入的data对象序列化为符合application/x-www-form-urlencoded要求的格式,还会自动对特殊字符做URL编码,所以可以直接正常运行
正确实现代码
const xhr = new XMLHttpRequest(); xhr.open('POST', 'php/get_data.php', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); let packg = { schema: 'string', table: 'anotherString' }; const packgJSON = JSON.stringify(packg); // 核心修改:手动序列化为urlencoded格式,对值做URL编码 const postData = `content=${encodeURIComponent(packgJSON)}`; xhr.send(postData);
修改说明
- 用模板字符串拼接出
content=xxx的格式,和你jQuery代码中传入的data结构完全对应 - 用
encodeURIComponent()对JSON字符串做编码,避免JSON中的引号、冒号等特殊字符破坏application/x-www-form-urlencoded的格式规则 - 如果需要传多个参数,用
&拼接即可,示例:const postData =content=${encodeURIComponent(val1)}&otherKey=${encodeURIComponent(val2)}``
内容的提问来源于stack exchange,提问作者d_araujo
相关产品推荐
相关产品推荐

