注册时:js的ajax实现局部刷新验证用户名

注册时填写用户名用的input标签如下:

<input type="text" onblur="checkName(this,'white')" name="name" id="name" placeholder="例如:小仙女"/>

onblur:表单元素属性,元素失去焦点时触发。

js代码:

/* ajax验证用户名 */

function checkName(obj,color){

    obj.style.background=color;

    var name=document.getElementById("name").value;

    var xmlHttp;

/* 下面的if(){} else{} 解决IE浏览器兼容问题 */

    if(window.XMLHttpRequest){

        xmlHttp=new XMLHttpRequest();

    }else{

        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

    }

/* 三个参数分别表示:method:提交方式,url:访问路径,boolean:true表示异步执行,false表示不异步执行,就是去了局部刷新的效果 */

    xmlHttp.open("get","ajax?name="+name,true);

    xmlHttp.onreadystatechange=function(){

/* 准备响应 */

        if(xmlHttp.readyState==4 && xmlHttp.status==200){

            var dataObj=eval("("+xmlHttp.responseText+")");

            if(dataObj.exist){

                alert("该用户名已经存在");

            }else if(name==""){

               alert("请填写用户名");

            }else{

               alert("该用户名合适");

            }

        }

    };

    xmlHttp.send();

}

Servlet代码:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        /**

         * 用户注册时检验用户名是否已存在

         */

        PrintWriter out;

        UserDao userDao = new UserDao();

        try {

            out = resp.getWriter();

            String userName=req.getParameter("name");

            JSONObject resultJson=new JSONObject();

            if(userName.equals(userDao.getUserName(userName))){

                resultJson.put("exist", true);

            }else{

                resultJson.put("exist", false);

            }

           //可以用String字符串来返回,没必要用json数据

            out.println(resultJson);

            out.flush();

            out.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

}

猜你喜欢

转载自blog.csdn.net/wentingleng/article/details/75168734