When there are many form data items, it will be inefficient to manually obtain the values of the form items. Combined with the function serialize() provided by jQuery, we can quickly obtain the data and submit the form data.
Please look at the form below:
<form id="fm"> <table> <tr> <td>姓名</td> <td> <input type="text" name="name" /> </td> </tr> <tr> <td>年龄</td> <td> <input type="text" name="age" /> </td> </tr> <tr> <td>密码</td> <td> <input type="password" name="password" /> </td> </tr> <tr> <td>性别</td> <td> <input type="radio" name="sex" value="male" />男 <input type="radio" name="sex" value="female" />女 </td> </tr> <tr> <td>地区</td> <td> <select name="area"> <option value="heping">和平区</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" />电影 <input type="checkbox" name="hobby[]" value="music" />音乐 <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>
We can get the form data through the custom function getFormData(), please look at the example below:
$(function(){ $('#submit').click(function(){ //选取表单 var form = $('#fm'); //获取表单数据 var data = getFormData(form); //发送AJAX请求 $.post('test.php',data,function(data){ console.log('ok'); }); }); });
getFormData() is very easy to implement Simple:
function getFormData(form){ var data = form.serialize(); data = decodeURI(data); var arr = data.split('&'); 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; }
test.php The data received will be:
Array ( [name] => 3241324 [age] => m_admin [password] => 123 [sex] => male [area] => heping [hobby] => Array ( [0] => movie [1] => music ) [intro] => 321432423 )
It is the same as the data format submitted by the ordinary form, we can process it very conveniently!