2020-02-03-Ajax回调函数中页面无法跳转
问题描述
通过ajax实现登录功能,在回调函数中无法正常实现页面跳转。
问题代码
<#--以下已简化-->
<form id = "form">
<input type="tel" class="form-text" id="telNum" name="telNum" placeholder=" 输入手机号码"/>
<input type="password" class="form-text" id="password" name="password" placeholder=" 输入登录密码" />
<button type="submit" id="submit01" style="background-color: #259B24;width: 350px;height: 60px;font-size: 30px;color: white;">登录 </button>
</form>
$("#submit01").on("click", function(){
var data = {};
data.telNum = $.trim($("input[name=telNum]").val());
data.password = $.trim($("input[name=password]").val());
if(data.telNum == ''){
alert("请输入账号!");
return ;//return会重新加载页面
}
else {
if(data.password == ''){
alert("输入密码");
}else {
$.ajax({
url: "/loginReg",
type : "post",
dataType: "text",
data: data,
success: function (res) {
if (!(res == "ok")) {
alert(res);
}else {
window.location.href="/index";
}
}
});
}
}
});
解决方法
方式一
使用了ajax,不使用form表单。将html中from标签换成div标签,修改如下:
<div id="form">
<input type="tel" class="form-text" id="telNum" name="telNum" placeholder=" 输入手机号码"/>
<input type="password" class="form-text" id="password" name="password" placeholder=" 输入登录密码" />
<button type="submit" id="submit01" style="background-color: #259B24;width: 350px;height: 60px;font-size: 30px;color: white;">登录 </button>
</div>
方式二
在JS中,由于location.href的方法会刷新页面。正确的页面跳转写法如下:
$.ajax({
url: "/loginReg",
type : "post",
dataType: "text",
data: data,
success: function (res) {
if (!(res == "ok")) {
alert(res);
}else {
//window.location.href="/index";
$("#form").attr("action","/index");
}
}
});
参考链接
https://blog.csdn.net/qq_40350405/article/details/89488440
https://blog.csdn.net/TJ1454862/article/details/95796393
https://bbs.csdn.net/topics/390980470

浙公网安备 33010602011771号