Andy 胡

导航

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());
    }

posted on 2016-11-24 23:46  talkwah  阅读(254)  评论(0编辑  收藏  举报