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