form 转json,将form表单中的数据序列化数组后转换为Json


页面中引用了jquery,第一想到的就是序列化,但是序列化后的表单字段为a=1&b=2这种。

这里写一个jquery的扩展方法

$.fn.serializeObject = function()    
{    
   var o = {};    
   var a = this.serializeArray();    
   $.each(a, function() {    
       if (o[this.name]) {    
           if (!o[this.name].push) {    
               o[this.name] = [o[this.name]];    
           }    
           o[this.name].push(this.value || '');    
       } else {    
           o[this.name] = this.value || '';    
       }    
   });    
   return o;    
};  

这个方法是将表单序列化成json的。

 

像这样调用:

var para = $('form').serializeObject() ;   
para = JSON.stringify(para) ; 

先把表单数据序列化为一个json对象,然后将json对象转换成一个json字符串。

这样para就是一个json字符串啦。就可以发起请求了


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM