Webpage json (5) --- convert the value obtained by using the serialize () method to json

Source: Internet
Author: User

Form has a serialize () method that can serialize the value of the form. However, this method provided by jquery serializes the data in a format similar to the following: 

A = 1 & B = 2 & c = 3 & d = 4

Jquery does not provide a method to serialize form data to json, so we need to encapsulate it ourselves. The following code and test example are provided. First, write a js file:

$. AjaxSetup ({contentType: "application/x-www-form-urlencoded; charset = UTF-8 "}); var DataDeal = {// use $ ('# form') from form '). the value obtained by serialize () is converted to json formToJson: function (data) {data = data. replace (/&/g, "\", \ ""); data = data. replace (/=/g, "\": \ ""); data = "{\" "+ data +" \ "}"; return data ;},};

Usage: first import the above js file on the page, and then

Var data = $ ('# addf '). serialize (); // get the value data = decodeURIComponent (data, true); // prevent Chinese garbled var json = DataDeal. formToJson (data); // convert to json


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.