前端html页面
<div class="form-group">
<input type="text" class="form-control" placeholder="用户名" required="" id="userName">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="密码" required="" id="userPwd">
</div>
<input type="submit" class="btn btn-primary block full-width m-b" value="登录" onclick="userLogin()">
<script>
function userLogin() {
var userName = document.getElementById("userName").value;
var userPwd = document.getElementById("userPwd").value;
console.log(userName + " " + userPwd);
if (userName == null || userPwd == null) {
alert("请输入用户名和密码");
} else {
$.ajax({
async: true,
url: "/userLogin?userName=" + userName + "&userPwd=" + userPwd,
type: "get",
success: function (data) {
if (data == "0") {
alert("用户名或密码输入错误");
window.location.href = "/register";
return false;
} else if (data == "1") {
alert("登录成功");
window.location.href = "/index";
return false;
}
}
});
}
}
</script>
Ajax发送请求
$.ajax({
async: true,
url: "/userLogin?userName=" + userName + "&userPwd=" + userPwd,
type: "get",
success: function (data) {
if (data == "0") {
alert("用户名或密码输入错误");
window.location.href = "/register";
return false;
} else if (data == "1") {
alert("登录成功");
window.location.href = "/index";
return false;
}
}
});
- async:是否异步,true为异步,false为同步。
当async属性的值为false时是同步的,Ajax请求将整个浏览器锁死,只有ajax请求返回结果后,才执行ajax后面的alert语句。
当async属性的值为true时是异步的,即不会等待ajax请求返回的结果,会直接执行ajax后面的alert语句。
-
url:访问的路径,类似于form中的action ?后面为需要传的参数,不同参数之间用&来区分
-
type:类型,有post请求,get请求
GET 还是 POST?
与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用。
然而,在以下情况中,请使用 POST 请求:
1、无法使用缓存文件(更新服务器上的文件或数据库)
2、向服务器发送大量数据(POST 没有数据量限制)
3、发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠