将json转为复杂url参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//json转url参数
var parseParam = function(param, key) {
var paramStr = "";
if (param instanceof String || param instanceof Number || param instanceof Boolean) {
paramStr += "&" + key + "=" + encodeURIComponent(param);
} else {
$.each(param, function(i) {
var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
paramStr += '&' + parseParam(this, k);
});
}
return paramStr.substr(1);
};
var obj = {
"name": 'tom',
"class": {
"className": 'class1'
},
"classMates": [{
"name": 'lily'
}]
};
1
2
console.log(parseParam(obj));//name=tom&class.className=class1&classMates[0].name=lily
console.log(parseParam(obj, 'stu'));//stu.name=tom&stu.class.className=class1&stu.classMates[0].name=lily
坚持原创技术分享,您的支持将鼓励我继续创作!
  • 本文作者: Leo
  • 本文链接: https://xuebin.me/posts/4e473707.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!