做项目时,遇到个问题,现象是:需要 button 按钮点击请求后端返回数据,通过验证后再执行后续逻辑。
代码大致如下:
<form method="post"> | |
<input type="text" id="LoginInput_UserNameOrEmailAddress" placeholder="请输入用户名或邮箱" aria-label="UserNameOrEmailAddress"/> | |
<input type="password" id="LoginInput_Password" placeholder="请输入密码"/> | |
<abp-button type="submit" name="Action" value="Login">登录</abp-button> | |
</form> | |
$("button[name$='Action']").click(function (event) { | |
let url = window.location.host; | |
let loginParam = $("#LoginInput_UserNameOrEmailAddress").val(); | |
$.ajax({ | |
type: "GET", | |
async: false, // 使请求为同步,在执行 ajax 请求,不会做别的事 | |
url: `${document.location.protocol}//${url}/${loginParam}`, | |
dataType: "json", | |
success: function (data) { | |
console.log(data) | |
if (data.allowLogin == false) { | |
// 相关业务逻辑 | |
return false; | |
} | |
}, | |
error: function () { | |
return false; | |
} | |
}) | |
}) |
运行测试网络请求状态码是 200,但没有响应数据,说明请求是正常的。
查阅相关资料后发现原因出在 button 标签上,type=“submit”,至于为什么 type 为 submit 后 click 内的 ajax 请求没有响应数据这个问题还在研究中。不过只要知道哪里出问题就好办了,不需要知道具体原理也能解决。
我的思路:先把 type="submit" 改成 type=“button”。然后再请求里需要提交的地方,再提交表单。
修改后的代码如下:
<form method="post"> | |
<input type="text" id="LoginInput_UserNameOrEmailAddress" placeholder="请输入用户名或邮箱" aria-label="UserNameOrEmailAddress"/> | |
<input type="password" id="LoginInput_Password" placeholder="请输入密码"/> | |
<abp-button type="button" name="Action" value="Login">登录</abp-button> | |
</form> | |
$("button[name$='Action']").click(function (event) { | |
let url = window.location.host; | |
let loginParam = $("#LoginInput_UserNameOrEmailAddress").val(); | |
$.ajax({ | |
type: "GET", | |
async: false, // 使请求为同步,在执行 ajax 请求,不会做别的事 | |
url: `${document.location.protocol}//${url}/${loginParam}`, | |
dataType: "json", | |
success: function (data) { | |
if (data.allowLogin == false) { | |
// 相关业务逻辑 | |
return false; | |
} | |
else { | |
$("form:first").submit(); | |
} | |
}, | |
error: function () { | |
return false; | |
} | |
}) | |
}) |