How to convert a form from a JavaScript jQuery library to a JSON object _ jquery-js tutorial

Source: Internet
Author: User
This article describes how to convert a form from the JavaScript jQuery library to a JSON object, including how to solve the serialization space-time lattice problem, for more information, see the serialize method in Jquery. You can serialize a form into a "&" connection string, but do not provide a Json serialization method. However, we can write a plug-in implementation.

On the Internet, I saw someone using a replacement method. After serialize is first serialized, replace & with ":" and "'":

/*** Reset form * @ param formId form id */function resetQuery (formId) {var fid = "#" + formId; var str = $ (fid ). serialize (); // str = cardSelectDate = 3 & startdate = 2012-02-01 & enddate = 2012-02-04var ob = strToObj (str); alert (ob. startdate); // 2012-02-01} function strToObj (str) {str = str. replace (// g, "','"); str = str. replace (/=/g, "':'"); str = "({'" + str + "'})"; obj = eval (str ); return obj;}/*** reset form * @ param formId form id */function resetQuery (formId) {var fid = "#" + formId; var str = $ (fid ). serialize (); // str = cardSelectDate = 3 & startdate = 2012-02-01 & enddate = 2012-02-04 var ob = strToObj (str); alert (ob. startdate); // 2012-02-01} function strToObj (str) {str = str. replace (// g, "','"); str = str. replace (/=/g, "':'"); str = "({'" + str + "'})"; obj = eval (str ); return obj ;}

I personally feel that there is a bug in doing so.
My method is to first serialize serializeArray into an array and then encapsulate it as a Json object.
The following is a form:

 < form id = "myForm" action = "#" >< input name = "name" />< input name = "age" />< input type = "submit" />
  


The Jquery plug-in code is as follows:

( function ($){$.fn.serializeJson= function (){var serializeObj={};$( this .serializeArray()).each( function (){serializeObj[ this .name]= this .value;});return serializeObj;};})(jQuery);(function($){     $.fn.serializeJson=function(){       var serializeObj={};       $(this.serializeArray()).each(function(){         serializeObj[this.name]=this.value;       });       return serializeObj;     };   })(jQuery); 



The following is a test:

$("#myForm").bind("submit",function(e){e.preventDefault();console.log($( this ).serializeJson());});  e.preventDefault();   console.log($(this).serializeJson()); }); 

Test results:
Input a and B to submit and get the serialization result.

{age: "b",name: "a"}



The above plug-in cannot be applied to input controls with multiple values, such as check boxes and multiple select statements. Next, I will make further modifications to the plug-in so that it supports multiple selections. The Code is as follows:

( function ($){$.fn.serializeJson= function (){var serializeObj={};var array= this .serializeArray();var str= this .serialize();$(array).each( function (){if (serializeObj[ this .name]){if ($.isArray(serializeObj[ this .name])){serializeObj[ this .name].push( this .value);} else {serializeObj[ this .name]=[serializeObj[ this .name], this .value];}} else {serializeObj[ this .name]= this .value;}});return serializeObj;};})(jQuery);(function($){     $.fn.serializeJson=function(){       var serializeObj={};       var array=this.serializeArray();       var str=this.serialize();       $(array).each(function(){         if(serializeObj[this.name]){           if($.isArray(serializeObj[this.name])){             serializeObj[this.name].push(this.value);           }else{             serializeObj[this.name]=[serializeObj[this.name],this.value];           }         }else{           serializeObj[this.name]=this.value;          }       });       return serializeObj;     };   })(jQuery); 

Here, I encapsulate multiple values into a single value for processing. If you need to encapsulate multiple values as "," connected strings or other forms, modify the corresponding code on your own.

The test is as follows:
Form:

< form id = "myForm" action = "#" >< input name = "name" />< input name = "age" />< select multiple = "multiple" name = "interest" size = "2" >< option value = "interest1" > interest1 
 < option value = "interest2" > interest2 
 < option value = "interest3" > interest3 
 < option value = "interest4" > interest4 
 
 < input type = "checkbox" name = "vehicle" value = "Bike" /> I have a bike< input type = "checkbox" name = "vehicle" value = "Car" /> I have a car< input type = "submit" />
  

Test results:

{age: "aa",interest: ["interest2", "interest4"],name: "dd",vehicle:["Bike","Car"]}

Handling space during serialization

Jquery's serialize () method can be used to serialize individual tables. This is a convenient feature. However, the following problems may occur in actual use:

For example

 

After the serialize () method is executed, a string like ddd + 567 is obtained. That is, the serialization method of jquery escapes spaces and converts them to the plus sign.

Solution

Because the serialize () method escapes % 2B for the true "+", you can replace the symbols of the result after serialize.

For example

Script var a = $ ('$ frm1 '). serialize (); // serialization. By default, encodeURIComponent () is called to encode alert (a); // content = ddd ++ 567 ++ 987var B =. replace (// \\+/g, ""); // g indicates that B = decodeURIComponent (B) is replaced for all matching strings ); // decode the content after serialize alert (B); // content = ddd + 567 + 987 script

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.