Adding parameters and Json conversion code in Jquery _ jquery

Source: Internet
Author: User
Sometimes, we need to further convert it into a json expression. Refer to the Ext. urlDecode function in Ext, And we can implement a function used in jquery. In jquery, $ ("# myform") is used "). serialize () can construct the content of the form into a querystring. For example, expressions such as width = 1680 & height = 1050 can be converted to json
Expression {"width": "1680", "height": "1050 "}.
Sometimes, we need to further convert it into a json expression. Refer to the Ext. urlDecode function in Ext, we can implement a function used in jquery:

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, convert $. toJson (s) to Json Object.
If, in turn, the json expression is converted to the querystr parameter format, you can use the $. param () method, or implement one by yourself, for example, the following 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 ('');
};

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.