项目结构:
index.html:
<!DOCTYPE html> <html> <head> <title>ajax实例</title> <meta charset="UTF-8"> <script type="text/javascript" src="js/jquery-1.10.1.min.js"></script> <script type="text/javascript"> $(function(){ $("#userName").blur(function(){ var userName = $("#userName").val(); if(userName.length == 0){ $("#unMess").html("<font color=red>用户名不能为空</font>"); }else{ $.ajax({ type: "POST", url: "UserServlet", data: {userName:userName}, dataType:"json", //返回类型 success: function(r){ //假如上面的dataType写成dataType:"html", 那么就要进行下面的转换 //将json字符串转换成对象的两种方法: //方法一: r= eval("(" + r + ")"); //方法二: r=$.parseJSON(r); console.info(r); if(r.unMess == "1"){ $("#unMess").html("<font color=green>恭喜,用户名正确</font>"); }else{ $("#unMess").html("<font color=red>抱歉,用户名错误</font>"); } } }); } }); }); </script> </head> <body> <p> <font color=red>提示:</font>1、文本框得到焦点,没有输入,失去焦点后,显示”用户名不能为空“<br /> 2、文本框得到焦点,只有输入”dgh“,失去焦点后,才会显示”恭喜,用户名正确“,否则显示”抱歉,用户名错误“<br /> </p> <label for="userName">用户名:</label> <input type="text" id="userName" name="userName" /><span id="unMess"></span> </body> </html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <servlet> <servlet-name>UserServlet</servlet-name> <servlet-class>com.dgh.servlet.UserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UserServlet</servlet-name> <url-pattern>/UserServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
UserServlet.java:
package com.dgh.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UserServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置字符编码 request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String userName = request.getParameter("userName"); String unMess = ""; if("dgh".equals(userName)){ //返回1表示用户名正确 //{"":"","":""}这是json格式的字符串,在每个双引号之前要加转义字符"\" response.getWriter().write("{\"unMess\":\"1\"}"); }else { //返回0表示用户名错误 //{"":"","":""}这是json格式的字符串,在每个双引号之前要加转义字符"\" response.getWriter().write("{\"unMess\":\"0\"}"); } } }
index.html页面效果:
时间: 2024-10-27 06:29:24