如今有下面的的一個form表單:咱們須要將它裏面的數據內容轉化爲json格式:javascript
<form id="myForm"> <input type="text" name="name1" value="name1"/> <input type="text" name="name2" value="name2"/> <input type="text" name="name3" value="name3"/> <div><input type="submit" id="submitBtn"></div> </form>
首先咱們須要創建一個序列化表單的方法:html
$.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name] !== undefined) { 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; }; $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a,function(){ if(o[this.name] !== underfined) { 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; };
獲取表單中的數據:java
$("#submitBtn").on("click",function(){json
var formData = $("myForm").serializeObject();this
console.log(formData);code
});orm