//将form转为AJAX提交
function ajaxSubmit(frm, fn) {
var dataPara = getFormJson(frm);
$.ajax({
url: frm.action,
type: frm.method,
data: dataPara,
success: fn
});
}
//将form中的值转换为键值对。
function getFormJson(frm) {
var o = {};
var a = $(frm).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;
}
//调用
$(document).ready(function(){
$('#form1').bind('submit', function(){
ajaxSubmit(this, function(data){
//alert(data.message);
//window.location.href="index";
});
return false;
});
});
<form id="form1" method="post" action="xxx.action">
用户名:<input type="text" name="username">
密码: <input type="password" name="userpwd">
<input type="submit" value="ajax提交">
</form>