案例如下:
<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="1">北京</option>
<option value="2">上海</option>
<option value="3">广州</option>
<option value="4">深圳</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>
我们可以通过自定义函数getFormData()来获取表单的数据,请看下面的例子:
$(function(){
$('#submit').click(function(){
//选取表单
var form = $('#fm');
//获取表单数据
var data = getFormData(form);
//发送AJAX请求
$.post('demo.php',data,function(data){
console.log('ok');
});
});
});
getFormData()的实现很简单:
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;
}
/**
demo.php接收到的数据将会是:
Array
(
[name] => 3241324
[age] => m_admin
[password] => 123
[sex] => male
[area] => 1
[hobby] => Array
(
[0] => movie
[1] => music
)
[intro] => nihao
)
**/