AJAX学习总结

login.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%
 3     String path = request.getContextPath();
 4     String basePath = request.getScheme() + "://"
 5             + request.getServerName() + ":" + request.getServerPort()
 6             + path + "/";
 7 %>
 8 
 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
10 <html>
11     <head>
12         <base href="<%=basePath%>">
13 
14         <title>My JSP 'login.jsp' starting page</title>
15 
16         <meta http-equiv="pragma" content="no-cache">
17         <meta http-equiv="cache-control" content="no-cache">
18         <meta http-equiv="expires" content="0">
19         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
20         <meta http-equiv="description" content="This is my page">
21         <!--
22     <link rel="stylesheet" type="text/css" href="styles.css">
23     -->
24 
25         <script type="text/javascript" src="js/jquery-1.8.3.js">
26 </script>
27     </head>
28     <script type="text/javascript">
29 function chkName() {
30     var name = $("#username").val();
31     alert(name);
32 //name为输入的值
33     var xmlhttp;
34     if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
35         xmlhttp = new XMLHttpRequest();
36     } else {// code for IE6, IE5
37         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
38     }
39     //这一段代码可以直接使用
40     xmlhttp.open("get","server.jsp?name="+name,true);
41     xmlhttp.send();
42     
43     xmlhttp.onreadystatechange=function(){
44     
45       if(xmlhttp.readyState==4&&xmlhttp.status==200){
46     
47          var str=xmlhttp.responseText;//成功响应结束,取得响应文本
48          //alert("xx"+$.trim(str)+"xx");
49          if($.trim(str)=="true"){//需要去空格
50             $("#msg").html("用户已存在!");
51          }else{
52            $("#msg").html("此用户可用!");
53          }
54       }
55     }
56     
57     
58 }
59 </script>
60     <body>
61         <form action="login.action" method="post">
62             <div>
63                 用户名:
64                 <input name="username" type="text" value="" id="username"
65                     onblur="chkName()" />
66                 <span id="msg"></span>
67             </div>
68 
69             <input type="submit" value="提交" />
70         </form>
71     </body>
72 </html>

server.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 
 3 <%
 4    String name=request.getParameter("name");
 5    if("sa".equals(name)){
 6      out.print("true");
 7    }else{
 8      out.print("false");
 9    }
10 
11 %>
原文地址:https://www.cnblogs.com/jimorulang/p/5587340.html