Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

A way to convert forms in JavaScript's jQuery library into JSON objects


May 08, 2021 JSON


Table of contents


Convert the form in JavaScript's jQuery library into a JSON object

As you know, there is a serialize method in Jquery that serializes the form into a string of "and" connections, but does not provide a method for serializing as Johnson. However, we can write a plug-in implementation.

Someone has replaced it with ":","" after serializing it with a replacement method:

/**
* 重置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;
}
/** 
   * 重置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;  
  }  

But there are bugs in doing so.

The alternative is to serialize the array with the serializeArray and encapsulate it as a Johnson object.

Here's the form:

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

Jquery plug-in code:

( 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); 

Try it out:

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

Test results:

Enter a, b commit to get serialized results:

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

Further optimization

The plug-in above cannot be applied to input controls with multiple values, such as check boxes, multi-selected selects. B elow, the plug-in will be further modified to allow it to support multiple selection. 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, the multiple-selected values are encapsulated as a numeric value for processing. If you need to encapsulate multiple-selected values as "," the string of the connection, or other forms, modify the code yourself.

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 >
< 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
< input type = "submit" />
</ form >
<form id="myForm" action="#"> 
  <input name="name"/> 
  <input name="age"/> 
  <select multiple="multiple" name="interest" size="2"> 
    <option value ="interest1">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 
  <input type="submit"/> 
</form> 
< form id = "myForm" action = "#" >
< input name = "name" />
< input name = "age" />
< select multiple = "multiple" name = "interest" size = "2" >
< option value = "interest1" > 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
< input type = "submit" />
</ form >
<form id="myForm" action="#"> 
  <input name="name"/> 
  <input name="age"/> 
  <select multiple="multiple" name="interest" size="2"> 
    <option value ="interest1">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 
  <input type="submit"/> 
</form> 

Test results:

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

The space problem when dealing with serialization

jquery's serialize() method, which serializes form items, would have been a convenient feature;

For example:

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

After executing the serialize() method, you get a string such as dd+567;

The workaround

Because the serialize() method escapes %2B to the real "plus" number, you can replace the results after the serialize() with symbols.

For example:

<input name="content" value="ddd + 567 + 987"/>
<script>
var a= $('$frm1').serialize(); //序列化,默认会调用encodeURIComponent()进行编码
alert(a); // content=ddd+++567+++987
var b = a.replace(/\\+/g," ");  // g表示对整个字符串中符合条件的都进行替换
b = decodeURIComponent(b); //对serialize后的内容进行解码
alert(b); // content=ddd + 567 + 987
</script>