首先需要导入js
<script src="js/jquery-3.6.0.js"></script>
编写后端接口
@RequestMapping("/login")
@ResponseBody
public String login(String name,String pwd){
String msg = "";
if(name!=null){
if(name.equals("admin"))
msg="OK";
else
msg="用户名错误";
}
if (pwd!=null){
if (pwd.equals("123456"))
msg="OK";
else
msg="密码错误";
}
return msg;
}
前端页面
<p>
用户名:<input type="text" id="name" onblur="a1()">
<span id="userInfo"></span>
</p>
<p>
密码:<input type="text" id="pwd" onblur="a2()">
<span id="pwdInfo"></span>
</p>
ajax格式
<script>
function a1() {
$.post({
url:"login",
data:{"name":$("#name").val()},
success:function (data) {
if(data.toString()==='OK')
$("#userInfo").css("color","green");
else
$("#userInfo").css("color","red");
$("#userInfo").html(data);
}
})
}
function a2() {
$.post({
url:"login",
data:{"pwd":$("#pwd").val()},
success:function (data) {
if(data.toString()==='OK')
$("#pwdInfo").css("color","green");
else
$("#pwdInfo").css("color","red");
$("#pwdInfo").html(data);
}
})
}
</script>
最终结果展示