当表单中有多条数据需要向后台传递时,一个一个的获取显然是不可取的办法,可以借助表单的serialize()方法获取。
html:
<form id="form"> <table> <tr> <td>姓名</td> <td> <input type="text" name="name" value="张三" /> </td> </tr> <tr> <td>性别</td> <td> <input type="radio" name="sex" value="male" checked />男 <input type="radio" name="sex" value="female" />女 </td> </tr> <tr> <td>地区</td> <td> <select name="area"> <option value="heping" selected>和平区</option> <option value="nankai">南开区</option> <option value="xiqing">西青区</option> <option value="hexi">河西区</option> </select> </td> </tr> <tr> <td>爱好</td> <td> <input type="checkbox" name="hobby[]" value="movie" checked />电影 <input type="checkbox" name="hobby[]" value="music" checked/>音乐 <input type="checkbox" name="hobby[]" value="basketball" />篮球 </td> </tr> <tr> <td>个人介绍</td> <td> <textarea name="intro">个人介绍一下吧</textarea> </td> </tr> <tr> <td></td> <td> <input type="button" value="提交" id="submit" /> </td> </tr> </table> </form>
$(function(){ $("#submit").click(function(){ var form=$("#form"); var data=getFormData(form); $.ajax({ //注意测试一下传输的data数据是js对象还是json对象格式 }) }) // 获取表单数据 function getFormData(form){ var data=form.serialize(); data=decodeURI(data); //name=张三&sex=male&area=heping&hobby[]=movie&hobby[]=music&intro=个人介绍一下吧 var arr=data.split("&"); //["name=张三", "sex=male", "area=heping", "hobby[]=movie", "hobby[]=music", "intro=个人介绍一下吧"] var item,key,value,newData={}; for(var i=0;i<arr.length;i++){ item=arr[i].split("="); key=item[0]; value=item[1]; if(key.indexOf("[]")!=-1){ key=key.replace("[]",""); if(!newData[key]){ newData[key]=[]; } newData[key].push(value); }else{ newData[key]=value; } } return newData; //{name: "张三", sex: "male", area: "heping", hobby: (2) ["movie", "music"], intro: "个人介绍一下吧"} } })