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