传统Ajax的工作流程(以检测新用户id是否可用为例)

2016-12-26 11:15:23来源:CSDN作者:CrazyLai1996人点击

//页面<!DOCTYPE html><html><head><script>    var http_request=false;    function createRequest(){        //非IE浏览器        if(window.XMLHttpRequest){        http_request=new XMLHttpRequest();        }        //IE浏览器        else if(window.ActiveXObject){            try{                http_request=new ActiveXObject("Msxml2.XMLHTTP");            }            catch(e){                try{                    http_request=new ActiveXObject("Microsoft.XMLHTTP");                }                catch(e){                    http_request=false;                }            }        }    }    function checkId(id){        createRequest();        if(!http_request){            alert("创建XMLHttpRequest实例失败!");            return false;        }        http_request.onreadystatechange=getResult;//调用返回结果处理函数        http_request.open('GET',"CheckServlet?userid="+id,true);//采用异步方式发送GET方式请求        http_request.send(null);//发送请求        document.getElementById("msg").innerHTML="正在验证......";    }    function getResult(){        //判断请求状态        if(http_request.readyState==4){            //请求成功            if(http_request.status==200){                var text=http_request.responseText;//获取返回结果                if(text=="true"){                    flag=false;                    document.getElementById("msg").innerHTML="用户ID已存在";                }                else{                    flag=true;                    document.getElementById("msg").innerHTML="此用户ID可供使用";                }            }        }    }</script></head><body><form>  用户ID:<input type="text" onblur="checkId(this.value)"/><span id="msg"></span> </form></body></html>

//CheckServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding(“UTF-8”);
response.setContentType(“text/html”);
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
PrintWriter out=response.getWriter();
String userid=request.getParameter(“userid”);//获取请求参数
if(“123”.equals(userid))
{
out.print(“true”);
}
else
{
out.println(“false”);
}
}

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台