如何将嵌套JSON对象转为URL查询字符串以通过AJAX传递?
解决嵌套JSON对象转URL查询字符串的问题
首先,你的问题根源在于当前的postAjax函数在处理嵌套对象时,只是简单调用了encodeURIComponent(data[k])——而对象直接转字符串会默认输出[object Object]。像jQuery这类库之所以能让服务端直接解析嵌套结构,是因为它们会把嵌套对象序列化成带方括号的键格式(比如p2[test_name]=Hello%20World),PHP的$_POST会自动识别这种格式并解析成嵌套数组。
实现递归序列化函数
你需要替换原来的参数处理逻辑,写一个递归函数来遍历嵌套对象,生成符合后端解析规则的查询字符串:
function serializeData(data) { const params = []; function encode(key, value) { // 处理数组:遍历每个元素,生成 key[index] 的格式 if (Array.isArray(value)) { value.forEach((item, index) => { encode(`${key}[${index}]`, item); }); return; } // 处理嵌套对象:遍历每个子键,生成 key[subKey] 的格式 if (typeof value === 'object' && value !== null) { Object.keys(value).forEach(subKey => { encode(`${key}[${subKey}]`, value[subKey]); }); return; } // 普通类型直接编码拼接 params.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`); } Object.keys(data).forEach(key => { encode(key, data[key]); }); return params.join('&'); }
修改后的postAjax函数
把原来的参数处理部分替换成上面的序列化函数即可:
function postAjax(url, data, success) { const params = typeof data === 'string' ? data : serializeData(data); const xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); xhr.open('POST', url); xhr.onreadystatechange = function() { if (xhr.readyState > 3 && xhr.status === 200) { success(xhr.responseText); } }; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(params); return xhr; }
测试嵌套对象传递
现在调用嵌套对象的场景:
postAjax(url, { p1: 1, p2: {'test_name':'Hello World', 'test_num': 123} }, function(data){ console.log(data); });
服务端用print_r($_POST)会输出:
Array ( [p1] => 1 [p2] => Array ( [test_name] => Hello World [test_num] => 123 ) )
为什么jQuery能做到?
jQuery的$.param()方法核心逻辑和上面的serializeData一致:
- 递归遍历对象或数组
- 对嵌套的键添加方括号后缀(比如
parent[childKey]) - 数组则用
parent[index]的格式 - 最终生成符合
application/x-www-form-urlencoded规范的字符串,PHP、Node.js等主流后端框架都能自动解析成嵌套结构
这样就不用手动在服务端解码JSON字符串,完全复刻了jQuery的使用体验。
内容的提问来源于stack exchange,提问作者Reza Amya
相关产品推荐
相关产品推荐

