Convert forms in JavaScript's jQuery library to JSON objects
Everyone knows that there is a serialize method in Jquery , which can serialize the form into a string connected by "&", but it does not provide a method to serialize it into Json. However, we can write a plugin implementation.
Some people use the replacement method, first use serialize to serialize, and replace & with ":", "'":
/**
* 重置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 doing so has bugs.
The other method is to use serializeArray to serialize it into an array first, and then encapsulate it into a Json object.
Here is 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 plugin 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);
have a test:
$("#myForm").bind("submit",function(e){
e.preventDefault();
console.log($( this ).serializeJson());
});
e.preventDefault();
console.log($(this).serializeJson());
});
Test Results:
Enter a, submit b, and get the serialized result:
{age: "b",name: "a"}
advanced optimization
The above plug-ins cannot be applied to input controls with multiple values, such as check boxes and multi-select selects. Next, make further modifications to the plug-in to allow it to support multiple selections. code show as below:
( 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 multi-choice value is packaged as a value for processing. If you need to encapsulate the multi-choice value into a string connected by "," or other forms when you use it, please modify the corresponding 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"]}
Dealing with whitespace issues when serializing
jquery's serialize() method can serialize form items, which is a very convenient function; but sometimes the following problems occur in actual use:
For example:
<input name="content" value="ddd 567"/>
After executing the serialize() method, what is obtained is a string like ddd+567; that is, the serialization method of jquery escapes the space and converts it into a + sign.
Solution
Since the serialize() method escapes the real "+" sign as %2B, the result after serialize() can be replaced by 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>