首页 > 代码库 > 将json格式转为url参数格式的方法(xjl456852整理修改)

将json格式转为url参数格式的方法(xjl456852整理修改)

测试页面:
  1. <html>
  2. <head>
  3. <script type="text/javascript" src="jquery-1.11.3.min.js"></script>
  4. </head>
  5. <body>
  6. <div id="div1">
  7. <button onclick="test1()">
  8. t1
  9. </button>
  10. <button onclick="test2()">
  11. t2
  12. </button>
  13. </div>
  14. </body>
  15. <script type="text/javascript">
  16. var parseParam = function(param, key) {
  17. var paramStr = "";
  18. if (typeof param == ‘string‘ || typeof param == ‘number‘ || typeof param == ‘boolean‘) {
  19. paramStr += "&" + key + "=" + encodeURIComponent(param);
  20. } else {
  21. $.each(param, function(i,tmp) {
  22. var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
  23. paramStr += ‘&‘ + parseParam(tmp, k);
  24. });
  25. }
  26. return paramStr.substr(1);
  27. };
  28. function test1() {
  29. console.log(parseParam({a:"12",b:123}));
  30. }
  31. function test2() {
  32. console.log(parseParam({a:"12",b:123},"user"));
  33. }
  34. </script>
  35. </html>

测试结果:
a=12&b=123
user.a=12&user.b=123


null


将json格式转为url参数格式的方法(xjl456852整理修改)