如何将JS对象转为合法JSON字符串并解决jQuery AJAX传参异常问题
问题原因
- jQuery的
$.ajax发送POST请求时,默认Content-Type请求头为application/x-www-form-urlencoded,该格式下传输的数据会被解析为表单键值对。 - 你直接传入
JSON.stringify生成的JSON字符串作为data参数时,jQuery会把整个JSON字符串识别为表单的键名,对应值为空,所以后端收到的请求体就是将完整JSON串作为key、空字符串作为value的异常结构。 - 额外说明:
JSON.stringify输出的压缩无换行格式是完全合法的JSON,你提到的带缩进换行的格式仅为可读性优化的展示效果,不影响数据有效性,接口传输用压缩格式性能更优。
解决方案
根据后端接口要求的接收格式,二选一即可:
方案1:发送JSON格式请求体(适配后端要求JSON入参的场景)
给$.ajax添加contentType配置指定请求体格式为JSON,修改后代码如下:
function graphApi(){ const apiValue = JSON.parse(localStorage.getItem('user')); console.log(apiValue,"apiValue"); const f = JSON.stringify(apiValue); console.log(f,"ffff") $.ajax({ type: "POST", data: f, url: "http://localhost:5000/File", // 新增以下配置 contentType: 'application/json; charset=utf-8', dataType: 'json', // 预期后端返回JSON格式数据,可根据实际返回调整 success: function (data) { console.log(data,"graph api"); } }) }
注意后端需要提前配置JSON请求体解析能力,比如Node.js Express框架需要启用app.use(express.json())中间件才能正确读取JSON格式的req.body。
方案2:发送表单格式请求体(适配后端要求表单入参的场景)
不需要对JS对象做JSON.stringify处理,直接传入原始JS对象作为data参数即可:
function graphApi(){ const apiValue = JSON.parse(localStorage.getItem('user')); console.log(apiValue,"apiValue"); $.ajax({ type: "POST", data: apiValue, // 直接传原始对象,无需转JSON字符串 url: "http://localhost:5000/File", success: function (data) { console.log(data,"graph api"); } }) }
该场景下后端需要配置表单数据解析能力,比如Node.js Express框架需要启用app.use(express.urlencoded({extended: true}))中间件才能正确读取表单格式的req.body。
内容的提问来源于stack exchange,提问作者fungusblacky
相关产品推荐
相关产品推荐

