How to convert a form in a JavaScript jquery library into a JSON object _jquery

Source: Internet
Author: User
Tags eval numeric value serialization jquery library

You know that there is a serialize method in jquery that you can serialize a form to a "&" concatenated string without providing a way to serialize to JSON. However, we can write a plugin implementation.
 
I saw someone use the replacement method on the Internet, first after serialize serialization, replace & with ":", "'":

/** * Reset Form form * @param formid form ID/function Resetquery (formid) {var fid = "#" + for
MId;
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;  
    /** * Reset Form 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; }  

Personally feel that there is a bug in doing so.
My approach is to first serialize to an array with Serializearray and then encapsulate it as a JSON object.
Here is the form:

 < form ID = "MyForm" action = "#" >
< input name = ' name '/>
< input name = ' age '/>
< in Put type = "Submit"/>
</form >

<form id= "MyForm" action= "#" > 
  <input name= "name"/> 
  <input name= "age"/> 
  <input type= "Submit"/> 
</form> 


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 test:

$ ("#myForm"). Bind ("Submit", function (e) {

e.preventdefault ();
Console.log ($ (this). Serializejson ());

  E.preventdefault (); 
  Console.log ($ (this). Serializejson ()); 
 

Test results:
Input A,b Commit, get serialization result

{age: ' B ', Name: ' A '}



The above plugin cannot be applied to input controls with multiple values, such as check boxes, multiple select selections. Next, I'll make further changes to the plugin to support multiple selections. The code is as follows:

(function ($) {$.fn.serializejson= function () {var serializeobj={}; var array= this. Serializearray (); var str= this. s
Erialize (); $ (array). each (function () {if (serializeobj[. Name]) {if ($.isarray (serializeobj[. Name))} {serializeobj[this
. Name].push (this. value); else {serializeobj[this. name]=[serializeobj['. Name], this. value];}
else {serializeobj[this. name]=. 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 the multiple selections as a numeric value for processing. If you need to encapsulate multiple selections of values as "," strings or other forms, modify the code accordingly. The
 
test is as follows:
form:
 

< form ID = "MyForm" action = "#" > < input name = "Name"/> < input name = "Age"/> < select Multip Le = "multiple" name = "interest" size = "2" > < option value = "Interest1" > Interest1 </option > < op 
tion value = "Interest2" > Interest2 </option > < option value = "Interest3" > interest3 </option > < option value = "Interest4" > Interest4 </option > </Select > < input type = "checkbox" name = "V"
Ehicle ' value = ' Bike '/> I have a Bike < input type = ' checkbox ' name = ' vehicle ' value = ' car '/> I have a car < input type = "Submit"/> </form > <form id= "myForm" action= "#" > <input name= "name"/> ; input name= "age"/> <select multiple= "multiple" name= "interest" size= "2" > <option value = "Interest1" &G t;interest1</option> <option value = "Interest2" >interest2</option> <option value= "Interest3 ">interest3</option> <option value= "Interest4" >interest4</option> </select> <input type= "checkbox" Name= " Vehicle "value=" Bike "/> I have a Bike <input type=" checkbox "name=" vehicle "value=" car "/> I have a car &l 

 T;input type= "Submit"/> </form>

Test results:

{age: ' AA ', interest: [' interest2 ', ' Interest4 '],name: ' dd ', vehicle:[' Bike ', ' Car ']}

To handle space issues when serializing

The serialize () method of jquery, which can serialize a table item, is a handy feature, but sometimes the following problems occur in actual use:

For example

<input name= "Content" value= "ddd 567"/>

After the serialize () method is executed, a string of ddd+567 is obtained, that is, the jquery serialization method escapes the space and converts it to the + number.

Solving method

Since the serialize () method escapes%2b for the true "+" number, the result of serialize () can be replaced by a symbol.

For example

<input name= "Content" value= "DDD + 567 + 987"/>

<script>

var a= $ (' $frm 1 '). Serialize ()//serialization, By default, encodeURIComponent () is invoked to encode
alert (a);//content=ddd+++567+++987
var b = a.replace (/\\+/g, "");  G means to replace the entire string in accordance with the conditions of
B = decodeuricomponent (b);//decode the contents after serialize
alert (b);//content=ddd + 567 + 987

</script>

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.