將JavaScript的jQuery庫中表單轉(zhuǎn)化為JSON對象的方法

2022-05-17 14:29 更新

將JavaScript的jQuery庫中表單轉(zhuǎn)化為JSON對象

大家知道Jquery中有serialize方法,可以將表單序列化為一個“&”連接的字符串,但卻沒有提供序列化為Json的方法。不過,我們可以寫一個插件實現(xiàn)。

有人用替換的方法,先用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序列化為數(shù)組,再封裝為Json對象。

下面是表單:

< 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插件代碼:

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

測試結(jié)果:

輸入a,b提交,得到序列化結(jié)果:

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

進(jìn)一步優(yōu)化

上面的插件,不能適用于有多個值的輸入控件,例如復(fù)選框、多選的select。下面,將插件做進(jìn)一步的修改,讓其支持多選。代碼如下:

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

這里,將多選的值封裝為一個數(shù)值來進(jìn)行處理。如果大家使用的時候需要將多選的值封裝為“,"連接的字符串或者其他形式,請自行修改相應(yīng)代碼。

測試如下:

表單:
< 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> 

測試結(jié)果:

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

處理序列化時的空格問題

jquery的 serialize()方法,可以對表單項進(jìn)行序列化,這本來是很方便的一個功能;但是實際使用中有時會出現(xiàn)如下問題:

例如:

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

在執(zhí)行 serialize()方法后,得到的卻是  ddd+567這樣的字符串;即jquery的序列化方法對空格進(jìn)行了轉(zhuǎn)義,轉(zhuǎn)換成了 + 號。

解決方法

由于serialize()方法對真正的“+”號轉(zhuǎn)義的是 %2B,所以可以對serialize()后的結(jié)果進(jìn)行符號替換。

例如:

<input name="content" value="ddd + 567 + 987"/>
<script>
var a= $('$frm1').serialize(); //序列化,默認(rèn)會調(diào)用encodeURIComponent()進(jìn)行編碼
alert(a); // content=ddd+++567+++987
var b = a.replace(/\\+/g," ");  // g表示對整個字符串中符合條件的都進(jìn)行替換
b = decodeURIComponent(b); //對serialize后的內(nèi)容進(jìn)行解碼
alert(b); // content=ddd + 567 + 987
</script>
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號