首页 > 代码库 > Js_Ajax_用户名检测

Js_Ajax_用户名检测

输入"root",OK;输入其它,Error

ajax.jsp

    var xhr;    function createXhr() {        if (window.XMLHttpRequest) {            xhr = new XMLHttpRequest();        } else {            xhr = new ActiveXObject("Microsoft.XMLHTTP");        }    }        function chk(elm) {        var name = elm.value;        createXhr();        xhr.onreadystatechange = callback;        xhr.open("get", "AjaxServlet?para="+name, true);        xhr.send(null);    }    function callback() {        if (xhr.readyState == 4) {            if (xhr.status == 200) {                var t = xhr.responseText;                //文本 --> Json                var json = eval("(" + t + ")");                var elmCmt=document.getElementById("cmt")                if(json.result){                    elmCmt.innerText="OK";                }else{                    elmCmt.innerText="ERR";                }            }        }    }
<body>    <input type="text" onblur="chk(this)">    <span id="cmt" style="color:red"></span>    <br>    <input type="text"></body>

AjaxServlet.java

    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {            response.setCharacterEncoding("utf-8");            AhJson aj = new AhJson();            String para=request.getParameter("para");            JSONObject jo = new JSONObject();            if("root".equals(para) ){                jo.put("result", true);            }else{                jo.put("result", false);            }                        response.getWriter().write(jo.toString());    }

技术分享

Js_Ajax_用户名检测