日期:2014-05-16 浏览次数:20550 次
function getXmlHttpRequest(){ var xhr=null; if(window.XMLHttpRequest){ //非ie xhr=new XMLHttpRequest(); }else{ //从这里也可以看出微软的嚣张跋扈 xhr=new ActiveXObject("Microsoft.XMLHTTP"); } return xhr; }
function checkUsername() { //创建checkname.do request var xhr=getXmlHttpRequest(); var username=document.getElementById("username").value; var url="checkusername?username="+username; xhr.open("get",url,true);//true,为异步,可以在响应回来之前进行其它操作;默认为true //注册响应函数 xhr.onreadystatechange=function(){ //请求处理完毕后执行以下代码 //xhr有5种状态,0到4,分别代表(0)请求未初始化,(1)请求已初始化但未发送,(2)请求已发送,(3)请求处理中,(4)请求处理完毕 if(xhr.readyState==4){ //响应处理, 获取服务器返回的Text var text=xhr.responseText; document.getElementById("name_msg").innerHTML=text; } } //发送请求 xhr.send(null); }
<form method="post" action="checkusername"> username: <input name="username" id="username" onblur="checkusername()" /> <span id="name_msg" style="color:red"></span> <br /> <input type="submit" value="OK" /> </form>
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 CheckUserNameServlet extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain;charset=utf-8");//text/plain 很重要 request.setCharacterEncoding("utf-8"); PrintWriter out=response.getWriter(); String username = request.getParameter("username"); System.out.println(username); if ("tom".equals(username)) {//为方便起见,直接给了一个 out.print("此用户名已被占用"); } else { out.print("可以使用"); } out.flush(); out.close(); } }