url参数为数组/对象

时间:2014-06-27 14:41:21

标签: jquery url

使用jQuery.param,我可以这样做:

var myObject = {
  a: {
    one: 1,
    two: 2,
    three: 3
  },
  b: [ 1, 2, 3 ]
};
var recursiveEncoded = $.param( myObject );
var recursiveDecoded = decodeURIComponent( $.param( myObject ) );

recursiveDecoded; // "a[]=foo&a[]=bar&b[]=1&b[]=2&b[]=3"

但是如何得到:

var myObject = {
  a: {
    one: 1,
    two: 2,
    three: 3
  },
  b: [ 1, 2, 3 ]
};

来自"a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3"

1 个答案:

答案 0 :(得分:1)

尝试

var myObject = {
  a: {
    one: 1,
    two: 2,
    three: 3
  },
  b: [ 1, 2, 3 ]
};

var json = JSON.stringify(myObject);
var _arr = decodeURIComponent($.param(JSON.parse(json)));
var arr = JSON.parse(JSON.stringify(_arr.split("=").join("&").split("&")));
var obj = [];
var tempObj = [];
var tempVals = [];    
$.each(arr, function(index, value) {
  if ( /\[/.test(value) ) {
    var props = value.split(/\[|\]/).slice(0, 2);
    tempObj.push(props);        
  };
    if ( !/\[/.test(value) ) {
    var vals = Number(value);
    tempVals.push(vals);
  };      
});    
$.when($.each(tempObj, function(index, value) {
   value.push(tempVals[index])
}))
.done(function(data) {
  $.each(data, function(index, value) {
    obj.push(value.filter(Boolean))
  });
});    
console.log(obj);

编辑(更新)

使用forked versionjquery BBQ $.deparam() method(不$.browser,在jsfiddle返回Uncaught TypeError: Cannot read property 'msie' of undefined),尝试

    var myObject = {
      a: {
        one: 1,
        two: 2,
        three: 3
      },
      b: [ 1, 2, 3 ]
    };

    var p = decodeURIComponent( $.param( myObject ));
    var d = $.deparam( p );
      console.log( p, d ); 
   // a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3 
   // Object {a: Object, b: Array[3]}

jsfiddle http://jsfiddle.net/guest271314/6P7tf/