Ajax应用:实现表单数据的验证
AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
https://code.jquery.com/jquery-3.6.0.js
第一步:创建login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>Title</title><script src="${pageContext.request.contextPath}/static/jquery-3.6.0.js"></script><script>function a1() {$.post({url: "${pageContext.request.contextPath}/a3",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: "${pageContext.request.contextPath}/a3",data: {"pwd": $("#pwd").val()},success: function (data) {if (data.toString() === "OK") {$("#pwdInfo").css("color", "green");} else {$("#pwdInfo").css("color", "red");}$("#pwdInfo").html(data);}})}</script></head><body><p>用户名:<input type="text" id="name" onblur="a1()"><span id="userInfo"></span>密码:<input type="password" id="pwd" onblur="a2()"><span id="pwdInfo"></span></p></body></html>
上面代码在页面创建了两个文本框,并添加onblur事件,里面执行a1()和a2()函数。
这两个函数执行了jQuery库中的Ajax方法。
$.post(),$get()既是jQuery.ajax()的简写,它传入了三个参数:
url: "${pageContext.request.contextPath}/t1",data: {"pwd": $("#pwd").val()},success: function (data) {if (data.toString() === "OK") {$("#pwdInfo").css("color", "green");} else {$("#pwdInfo").css("color", "red");}$("#pwdInfo").html(data);}
data:填入要传给服务器的数据,由键值对的形式填写
success:填入回调函数,可以对服务器返回的数据进行判断
第二步:编写服务器端的请求
("/t1")public String t1(String name, String pwd) {if (name != null) {//admin应该在数据库中查if ("admin".equals(name)) {msg = "OK";} else {msg = "用户名有误!";}}if (pwd != null) {//admin应该在数据库中查if ("123456".equals(pwd)) {msg = "OK";} else {msg = "密码有误!";}}return msg;}
效果如下:
