拓展 jQuery 的 serialize(),将 form 表单转化为 json 对象

jQuery 的 serialize() 方法经常会报 Uncaught TypeError: JSON.serializeObject is not a function 的错误,

 

原装的方法真的一点都不好用,所以我在我的引用文件里面扩展了 jQuery 的方法,可以直接用

var obj = $("#form").parseForm(); 变成 json 对象,然后直接扔给后台。

 

搜索引擎搜索如下关键字可以查找更多资料:

jquery如何将表单内容转为json对象 

 

 法1

//扩展jquery的格式化方法
$.fn.parseForm=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;
};

 

调用方法

var param = $("#insurInfoForm").parseForm();
$.ajax({
    url : contextPath+'/products/policyList',
    data : JSON.stringify(param),
    type : 'post',
    dataType : 'json',
    async : false,
    success : function(data) {
    
    }
});

 

 

法2

$.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;
};

 

调用方法参考上面~ 

 

 使用方法(前提:使用的地方引入 jQuery):

法1:在需要格式化表单的html文件或者js文件中引入上面的方法。

法2:将如上的方法放进一个公共的js文件,然后在使用地方引入改公共的 js 文件。

 

参考:

https://blog.csdn.net/sychel/article/details/50068557

https://www.jb51.net/article/140685.htm

https://blog.csdn.net/lovesomnus/article/details/78026586

https://www.cnblogs.com/hyl8218/archive/2013/06/27/3159178.html

https://stackoverflow.com/questions/8900587/jquery-serializeobject-is-not-a-function-only-in-firefox

 

全文完

:)

 

原文地址:

https://www.cnblogs.com/poterliu/p/10142758.html

 

posted @ 2018-12-24 14:42  poterliu  阅读(15490)  评论(0编辑  收藏  举报