Ajax异步更新网页(使用原生JavaScript)
一、页面代码
<!DOCTYPE html> <html> <head> <title>MyHtml.html</title> <meta name="keywords" content="keyword1,keyword2,keyword3"> <meta name="description" content="this is my page"> <meta name="content-type" content="text/html; charset=UTF-8"> <body> <table> <tr> <td>Login:</td> <td><input id="username" type="text" name="login"></td> </tr> <tr> <td>Password:</td> <td><input type="password" name="password" id="password"></td> </tr> <tr> <td colspan="2"><input type="submit"></td> </tr> </table> </body> </html>
二、JavaScript代码
<script type="text/javascript"> var xmlHttp; $(document).ready(function() { $("#username").keyup(function() { var value = $(this).val(); xmlHttp = createXMLHttp(); var url = "MyServlet1?username=" + value; xmlHttp.open("GET", url, true); xmlHttp.onreadystatechange = callback; xmlHttp.send(null); }); }); function createXMLHttp() { var xmlHttp; if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } return xmlHttp; } var callback = function() { if (xmlHttp.status == 200 && xmlHttp.readyState == 4) { var result = xmlHttp.responseText; if (result == "已使用") $("#username").css("border-color", "red"); else $("#username").css("border-color", "green"); } else { alert("出错"); } } </script>
三、servlet代码
package com.yh.myServlet; 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 MyServlet1 extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String userName = request.getParameter("username"); System.out.println(userName); if (userName.equals("yh")) { out.print("已使用"); } else { out.print("可使用"); } } }
四、配置servlet
<servlet> <servlet-name>MyServlet1</servlet-name> <servlet-class>com.yh.myServlet.MyServlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet1</servlet-name> <url-pattern>/Pages/MyServlet1</url-pattern> </servlet-mapping>
注:这个Pages是根据html页面的路径设置的