将JavaScript的jQuery库中表单转化为JSON对象的方法

将JavaScript的jQuery库中表单转化为JSON对象

大家知道Jquery中有serialize方法,可以将表单序列化为一个“&”连接的字符串,但却没有提供序列化为Json的方法。不过,我们可以写一个插件实现。

有人用替换的方法,先用serialize序列化后,将&替换成“:”、“‘”:

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

不过这样做有bug。

其他的方法是,先用serializeArray序列化为数组,再封装为Json对象。

下面是表单:

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

 

Jquery插件代码:

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

测试一下:

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

测试结果:

输入a,b提交,得到序列化结果:

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

进一步优化

上面的插件,不能适用于有多个值的输入控件,例如复选框、多选的select。下面,将插件做进一步的修改,让其支持多选。代码如下:

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

这里,将多选的值封装为一个数值来进行处理。如果大家使用的时候需要将多选的值封装为“,"连接的字符串或者其他形式,请自行修改相应代码。

测试如下:

表单:

< 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" />
I have a bike I have a car
< 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" />
I have a bike I have a car

测试结果:

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

处理序列化时的空格问题

jquery的 serialize()方法,可以对表单项进行序列化,这本来是很方便的一个功能;但是实际使用中有时会出现如下问题:

例如:

在执行 serialize()方法后,得到的却是  ddd+567这样的字符串;即jquery的序列化方法对空格进行了转义,转换成了 + 号。

解决方法

由于serialize()方法对真正的“+”号转义的是 %2B,所以可以对serialize()后的结果进行符号替换。

例如:

你可能感兴趣的:(JAVAI学习,javascript,jquery,前端)