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

2022-05-17 14:29 更新

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

大家知道Jquery中有serialize方法,可以將表單序列化為一個(gè)“&”連接的字符串,但卻沒有提供序列化為Json的方法。不過,我們可以寫一個(gè)插件實(shí)現(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對(duì)象。

下面是表單:

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

測(cè)試一下:

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

測(cè)試結(jié)果:

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

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

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

上面的插件,不能適用于有多個(gè)值的輸入控件,例如復(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); 

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

測(cè)試如下:

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

測(cè)試結(jié)果:

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

處理序列化時(shí)的空格問題

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

例如:

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

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

解決方法

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

例如:

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

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)