1.html
<form class="form-login">
<div class="form-group form-group-lg">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-user fa-lg fa-fw"></i></div>
<input type="number" class="form-control" name="mobile" id="mobile" placeholder="手机号" required>
</div>
</div>
<div class="error-msg" id="mobile-err"><i class="fa fa-exclamation-circle"></i><span></span></div>
<div class="form-group form-group-lg">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-lock fa-lg fa-fw"></i></div>
<input type="password" class="form-control" name="password" id="password" placeholder="密码" required>
</div>
</div>
<div class="error-msg" id="password-err"><i class="fa fa-exclamation-circle"></i><span></span></div>
<button type="submit" class="btn btn-lg btn-theme btn-block">登录</button>
<p class="register-a">没有账号,<a href="/register.html">立即注册</a></p>
</form>
2.js
2.次e代表的是不同事件,无法互相操作。
$(".btn btn-lg").on('click')(function(e){
e.preventDefault(); //e表示当前点击事件
})
$(".form-login").submit(function(e){
e.preventDefault(); //e 表示的是当前选中的表单的提交事件。阻止默认表单提交行为。
mobile = $("#mobile").val();
passwd = $("#password").val();
if (!mobile) {
$("#mobile-err span").html("请填写正确的手机号!");
$("#mobile-err").show();
return;
}
if (!passwd) {
$("#password-err span").html("请填写密码!");
$("#password-err").show();
return;
}
var data = {};
$(this).serializeArray().map(function(x){data[x.name] = x.value;});
var jsonData = JSON.stringify(data);
$.ajax({
url:"/api/login",
type:"POST",
data: jsonData,
contentType: "application/json",
dataType: "json",
headers:{
"X-XSRFTOKEN":getCookie("_xsrf"),
},
success: function (data) {
if ("0" == data.errno) {
location.href = "/";
return;
}
else {
$("#password-err span").html(data.errmsg);
$("#password-err").show();
return;
}
}
});
});