第一个Ajax入门示例,注册页面,当输入用户名时,异步发送请求验证用户名是否可以用。
JSP页面代码如下:
<html> <head> <title>第一个Ajax示例,验证用户名是否使用</title> <script type="text/javascript"> /* Create a new XMLHttpRequest object to talk to the Web server */ var xmlHttp = false; /*@cc_on @*/ /*@if (@_jscript_version >= 5) try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { xmlHttp = false; } } @end @*/ if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); } function callServer() { var username = document.getElementById("username").value; if ((username == null) || (username == "")) return; var url = "servlet/UsernameServlet?username="+escape(escape(username)); xmlHttp.open("GET", url, true); xmlHttp.onreadystatechange = updatePage; xmlHttp.send(null); } function updatePage() { if (xmlHttp.readyState == 4 ) { if(xmlHttp.status ==200){ var response = xmlHttp.responseText; alert(response); document.getElementById("msg").innerHTML = response;/* alert("headers:"+xmlHttp.getAllResponseHeaders()); alert("Content-Length:"+xmlHttp.getResponseHeader("Content-Length")); alert("Content-Type:"+xmlHttp.getResponseHeader("Content-Type")); alert("Date:"+xmlHttp.getResponseHeader("Date")); alert("Server:"+xmlHttp.getResponseHeader("Server"));*/ }else{ alert("status:"+xmlHttp.status); } } } </script> </head> <body> <form action="servlet/UsernameServlet" method="post"> <p>用户名: <input type="text" name="username" id="username" size="25" onChange="callServer();" /><span id="msg"></span></p> <p>密码: <input type="text" name="pwd" size="25"/></p> <p><input type="submit" value="注册" /> </p> </form> </body></html>
UsernameServlet代码如下:
response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String username = request.getParameter("username"); username = unescape(username); if (username.equals("东东")) { out.print("此用户名已经被使用了,请输入其它名字"); } else { out.print("此用户名没有被使用"); }
out.flush(); out.close();
处理传递中文参数乱码的方法unescape(String str)如下:
public String unescape(String src) { // if (StringUtil.checkBlank(src).equals("")) { // return ""; // } StringBuffer tmp = new StringBuffer(); tmp.ensureCapacity(src.length()); int lastPos = 0, pos = 0; char ch; while (lastPos < src.length()) { pos = src.indexOf("%", lastPos); if (pos == lastPos) { if (src.charAt(pos + 1) == 'u') { ch = (char) Integer.parseInt(src .substring(pos + 2, pos + 6), 16); tmp.append(ch); lastPos = pos + 6; } else { ch = (char) Integer.parseInt(src .substring(pos + 1, pos + 3), 16); tmp.append(ch); lastPos = pos + 3; } } else { if (pos == -1) { tmp.append(src.substring(lastPos)); lastPos = src.length(); } else { tmp.append(src.substring(lastPos, pos)); lastPos = pos; } } } return tmp.toString(); }