在完善suggest功能的时候,遇到一个问题:form表单异步提交成功后应该让页面跳转到首页,但实际上页面只是刷新了但并未跳转.
起初的实现方式将提交按钮的类型设置成了button,通过onclick方法实现ajax提交并跳转页面
<form id="contact_form" class="cd-form floating-labels" method="post">
<div>
<input type="sumbit" value="Send Message" onclick="save()">
</div>
</form>
function save() {
// 你的逻辑
$.ajax({
type: "post",
url: url,
cache: false,
async: false,
dataType: "json",
data: data,
contentType: "application/json; charset=utf-8",
success: function (data) {
var code = data.result_code;
if ("200" == code) {
showMessage('成功提出建议...', 2000, true, '', '');
window.location.href = "/index";
return true;
} else {
showMessage('添加建议失败...', 2000, true, '', '');
return false;
}
}
});
}
这种方式成功的被submit阻止了跳转页面…,解决办法将submit替换成button,但是验证表单失效…
解决按钮类型是submit异步提交且表单验证有效的方式
<form action="/save_advice" id="contact_form" class="cd-form floating-labels" method="post" data-form="ajax">
<div class="icon">
<label class="cd-label" for="cd-name">昵称</label>
<input class="user" type="text" name="username" id="cd-name" required >
</div>
<div>
<input type="submit" value="Send Message" >
</div>
</form>
new VerJs({
form:"#contact_form",
success:function (data) {
var d = JSON.parse(data);
var code = d.result_code;
if ("200" == code) {
showMessage('成功提出建议...', 2000, true, '', '');
window.location.href = "/index";
return true;
} else {
showMessage('添加建议失败...', 2000, true, '', '');
return false;
}
},
fail:function (data) {
showMessage('添加建议异常...', 2000, true, '', '');
return false;
}
});
文章地址