今天在網上看到這個方法,感受很不錯,特地分享:ide
(function($){ $.fn.serializeJson=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; }; })(jQuery);
用法:測試
$("#myForm").bind("submit",function(e){ e.preventDefault(); console.log($(this).serializeJson()); });
測試用例:
this
<form id="myForm" action="#"> <input name="name"/> <input name="age"/> <select multiple="multiple" name="interest" size="2"> <option value ="interest1">interest1</option> <option value ="interest2">interest2</option> <option value="interest3">interest3</option> <option value="interest4">interest4</option> </select> <input type="checkbox" name="vehicle" value="Bike" /> I have a bike <input type="checkbox" name="vehicle" value="Car" /> I have a car <input type="submit"/> </form>
測試結果:rest
{age: "aa",interest: ["interest2", "interest4"],name: "dd",vehicle:["Bike","Car"]}