jQuery - 基於serializeArray的serializeObject

來源:互聯網
上載者:User

標籤:pass   相容   amp   logs   call   object   json   ace   lan   

原文地址

http://blog.csdn.net/flashdelover/article/details/8185775

 

jQuery有方法$.fn.serialize,可將表單序列化成字串;有方法$.fn.serializeArray,可將表單序列化成數組。
如果需要其序列化為JSON對象,那麼可以基於serializeArray編寫方法serializeObject輕鬆實現:

//work with jQuery 1.x  jQuery.prototype.serializeObject=function(){      var obj=new Object();      $.each(this.serializeArray(),function(index,param){          if(!(param.name in obj)){              obj[param.name]=param.value;          }      });      return obj;  }; 

 

註:當表單中參數出現同名時,serializeObject會取第一個,而忽略後續的。

設有

<form>      <input type="text" name="username" />      <input type="text" name="password" />  </form> 

 

 
jQuery("form").serialize(); //"username=&password="  jQuery("form").serializeArray(); //[{name:"username",value:""},{name:"password",value:""}]  jQuery("form").serializeObject(); //{username:"",password:""}  

 


20150125更新
===========
+ 此版本不再相容IE8
+ 修複一個邏輯錯誤

 

//work with jQuery 2.x  jQuery.prototype.serializeObject=function(){      var hasOwnProperty=Object.prototype.hasOwnProperty;      return this.serializeArray().reduce(function(data,pair){          if(!hasOwnProperty.call(data,pair.name)){              data[pair.name]=pair.value;          }          return data;      },{});  }; 

 


20150705更新
===========

+ 減少方法依賴,擴大相容範圍
+ 改用原生迴圈,提升代碼效能

 

//work with jQuery Compact 3.x  jQuery.prototype.serializeObject=function(){      var a,o,h,i,e;      a=this.serializeArray();      o={};      h=o.hasOwnProperty;      for(i=0;i<a.length;i++){          e=a[i];          if(!h.call(o,e.name)){              o[e.name]=e.value;          }      }      return o;  };  

 

jQuery - 基於serializeArray的serializeObject

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.