in serialize/unserialize, replace toNumber argument with isJSON argument
This commit is contained in:
parent
c718b0b8ef
commit
290d97cbee
1 changed files with 30 additions and 19 deletions
|
@ -149,16 +149,22 @@ Ox.methods = function(object, includePrototype) {
|
|||
|
||||
/*@
|
||||
Ox.serialize <f> Parses an object into query parameters
|
||||
> Ox.serialize({a: 1, b: 2, c: 3})
|
||||
'a=1&b=2&c=3'
|
||||
> Ox.serialize({a: -1, b: 2.3, c: [4, 5]})
|
||||
'a=-1&b=2.3&c=4,5'
|
||||
> Ox.serialize({string: 'foo', empty: {}, null: null, undefined: void 0})
|
||||
'string=foo'
|
||||
> Ox.serialize({a: 1, b: 2.3, c: -4})
|
||||
'a=1&b=2.3&c=-4'
|
||||
> Ox.serialize({a: [], n: null, o: {}, s: '', u: void 0})
|
||||
''
|
||||
> Ox.serialize({a: [1, 2], b: true, n: 1, o: {k: 'v'}, s: 'foo'}, true)
|
||||
'a=[1,2]&b=true&n=1&o={"k":"v"}&s="foo"'
|
||||
@*/
|
||||
Ox.serialize = function(object) {
|
||||
Ox.serialize = function(object, isJSON) {
|
||||
var ret = [];
|
||||
Ox.forEach(object, function(value, key) {
|
||||
var value;
|
||||
if (isJSON) {
|
||||
try {
|
||||
value = JSON.stringify(value);
|
||||
} catch(e) {}
|
||||
}
|
||||
if (!Ox.isEmpty(value) && !Ox.isNull(value) && !Ox.isUndefined(value)) {
|
||||
ret.push(key + '=' + value);
|
||||
}
|
||||
|
@ -168,23 +174,28 @@ Ox.serialize = function(object) {
|
|||
|
||||
/*@
|
||||
Ox.unserialize <f> Parses query parameters into an object
|
||||
> Ox.unserialize('a=1&b=2&c=3')
|
||||
{a: '1', b: '2', c: '3'}
|
||||
> Ox.unserialize('a=-1&b=2.3&c=4,5', true)
|
||||
{a: -1, b: 2.3, c: [4, 5]}
|
||||
> Ox.unserialize('a=1&b=&c&a=0', true)
|
||||
{a: 0}
|
||||
> Ox.unserialize('a=1&b=2.3&c=-4')
|
||||
{a: '1', b: '2.3', c: '-4'}
|
||||
> Ox.unserialize('a=foo&b=&c&a=bar')
|
||||
{a: 'bar'}
|
||||
> Ox.unserialize('a=[1,2]&b=true&n=1&o={"k":"v"}&s1="foo"&s2=bar', true)
|
||||
{a: [1, 2], b: true, n: 1, o: {k: 'v'}, s1: 'foo', s2: 'bar'}
|
||||
|
||||
@*/
|
||||
Ox.unserialize = function(string, toNumber) {
|
||||
Ox.unserialize = function(string, isJSON) {
|
||||
var ret = {};
|
||||
Ox.filter(string.split('&')).forEach(function(value) {
|
||||
var array = value.split('=');
|
||||
if (array[1]) {
|
||||
ret[array[0]] = !toNumber ? array[1]
|
||||
: array[1].indexOf(',') == -1 ? +array[1]
|
||||
: array[1].split(',').map(function(value) {
|
||||
return +value;
|
||||
});
|
||||
if (isJSON) {
|
||||
try {
|
||||
ret[array[0]] = JSON.parse(array[1]);
|
||||
} catch(e) {
|
||||
ret[array[0]] = array[1];
|
||||
}
|
||||
} else {
|
||||
ret[array[0]] = array[1];
|
||||
}
|
||||
}
|
||||
});
|
||||
return ret;
|
||||
|
|
Loading…
Reference in a new issue