Home >Web Front-end >JS Tutorial >Adding parameters and Json conversion code in Jquery_jquery

Adding parameters and Json conversion code in Jquery_jquery

WBOY
WBOYOriginal
2016-05-16 18:41:281008browse

In jquery, use $("#myform").serialize() to construct the content of the form into a querystring. For example, an expression such as width=1680&height=1050 can be converted into a json
expression {"width" :"1680","height":"1050"}.
Sometimes, we need to further convert it into a json expression. Referring to the Ext.urlDecode function in Ext, we can implement a corresponding function used in jquery:

Copy code The code is as follows:

$.par2Json=function(string, overwrite){
var obj = {},
pairs = string .split('&'),
d = decodeURIComponent,
name,
value;
$.each(pairs, function(i,pair) {
pair = pair.split( '=');
name = d(pair[0]);
value = d(pair[1]);
obj[name] = overwrite || !obj[name] ? value :
[].concat(obj[name]).concat(value);
});
return obj;
};

If necessary, you can Use $.toJson(s) to convert to Json Object.
If you convert the json expression into querystr parameter form, you can use the $.param() method, or we can implement one ourselves, such as the following code:
Copy code The code is as follows:

$.json2Par=function(o, pre){
var undef, buf = [], key, e = encodeURIComponent;
for(key in o){
undef = o[key]== 'undefined';
$.each(undef ? key : o[key], function(val, i){
buf.push("&", e(key), "=", (val != key || !undef) ? e(val) : "" );
});
}
if(!pre){
buf.shift();
pre = "";
}
return pre buf.join ('');
};
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn