JQuery-SerializeObject based on Serializearray

Source: Internet
Author: User
Tags hasownproperty

Original address

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

jquery has method $.fn.serialize, which can serialize forms into strings, and there are methods to serialize the form to an array of $.fn.serializearray.
If you need to serialize it to a JSON object, you can easily implement it based on the Serializearray authoring method SerializeObject:

// Work with JQuery 1.x   jquery.prototype.serializeobject=function() {      var obj=New  Object ();      $.each (this. Serializearray (),function(index,param) {          if inch obj)) {              Obj[param.name]=param.value;          }      });       return obj;  

Note: when the parameter in the form has the same name, the SerializeObject takes the first one and ignores the subsequent.

With

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

The

// "username=&password="   // [{name: "username", Value: ""},{name: "Password", Value: ""}]   // {username: "", Password: ""}  


20150125 Update
===========
+ This version is no longer compatible with IE8
+ Fix A logic error

// 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 Update
===========

+ Reduced method dependencies, extended compatibility range
+ Use native loops to improve code performance

 // 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++ =          a[i];  if  (! =e.value;  }}  return   o;  }; 

JQuery-SerializeObject based on Serializearray

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.