使用原生Ajax 验证用户名是否被注册
创建出注册信息:
<h1>注册信息</h1>
<input type="text" name="txtName" id="txtName"/> <span id="msg"></span><br/><input type="password" name="txtPwd"/>//创建myajx
function myajax(){
//01.定制出 xhr对象var xhr;//02.能力检测if(window.XMLHttpRequest){ //非IE浏览器 xhr=new XMLHttpRequest();}else{ //IE内核xhr=new ActiveXObject("Microsoft.XMLHttp");}var dom=document.getElementById("txtName");var myspan=document.getElementById("msg");var myval=dom.value;//03.构建请求地址//xhr.open("请求类型","请求地址","是否异步");xhr.open("get","<%=path%>/servlet/CheckUserServlet?uname="+myval,true);//04.设置回调函数 响应回来的数据xhr.onreadystatechange=function(){ //什么if(xhr.readyState==4&&xhr.status==200){ //获取响应数据var data=xhr.responseText;if(data=='OK'){ myspan.innerText="用户名已经被注册";}else{ myspan.innerText="用户名可以注册";}}};//05.用send真正的发送请求xhr.send(null);}
//用js的方式锁定焦点,并且失去焦点的时候执行myajax
window.οnlοad=function(){
var dom=document.getElementById("txtName");dom.οnblur=function(){ myajax();};};//ajax访问的servlet 内容
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { String name =request.getParameter("uname");if(name.equals("admin")){ response.getWriter().write("OK");}else{ response.getWriter().write("NO");}}