<%@ page contentType="text/html;charset=UTF-8" language="java"%> <html> <head> <title></title> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script> <script type="text/javascript"> $(function() { $(":input[name=‘username‘]").change(function() { var val = $(this).val(); val = $.trim(val); //去除填写数据的空格 if (val != "") { //如果填写数据不为空,就发送ajax数据请求 var url = "${pageContext.request.contextPath}/userName"; //请求地址为这个servlet地址 var args = { "userName" : val, "time" : new Date() //解决缓存问题 }; $.post(url, args, function(data) { $("#message").html(data); //加入在这个id号里面 }); } }); }) </script> </head> <body> <form action="" method="post"> username:<input type="text" name="username" /> <div id="message"></div> <!-- 预留空格写入后台返回的数据 --> <input type="submit" value="Submit"> </form> </body> </html>
servlet
package ajax; import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class UserNameServlet */ @WebServlet("/userName") public class UserNameServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<String> userNames = Arrays.asList("AAA", "BBB", "CCC"); //从数据库读取出来的数据 String userName = request.getParameter("userName"); //得到前台输入的值 String result = null; //定义返回的值 if (userNames.contains(userName)) { //判断数据库是否有前台输入的值 result = "<font color=‘red‘>可以登录</font>"; //有就将这个值返回到前台页面 } else { result = "<font color=‘green‘>不可以登陆</font>"; //没有将这个值返回到页面 } response.setContentType("text/html;charset=UTF-8"); //设置返回值的类型,设置编码 response.setCharacterEncoding("utf-8"); //设置编码 response.getWriter().print(result); //写在页面上 } }
时间: 2024-10-21 00:20:17