Ajax实现动态刷新页面(get)

第一步:写一个Util.js

function getXmlHttpRequest() {
    var xhr;

    try {
        // Firefox, Opera 8.0+, Safari
        xhr = new XMLHttpRequest();
    } catch (e) {

        // Internet Explorer
        try {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {

            try {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("您的浏览器不支持AJAX!");
                return false;
            }
        }
    }
    return xhr;
}

第二步写jsp注册界面

<script type="text/javascript">
        window.onload = function () {
            document.getElementById("name_r").onblur = function () {
                var name = document.getElementById("name_r").value;

//                发出异步请求
                var xhr = getXmlHttpRequest();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4) {
                        if (xhr.status == 200) {
                            //获取响应正文
                            document.getElementById("msg").innerHTML = xhr.responseText;
                        }
                    }
                }
                var url = "/servlet/CheckServlet?name_r=" + name + "&time=" + new Date().getTime();
                xhr.open("GET", url, true);
                xhr.send(null);
            }
        }
    script>

第三步:写一个Servlet

request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        BusinessService s = new BusinessServiceImpl();
        String username =  request.getParameter("name_r");
        if (username!=null){
            PrintWriter pw = null;
            try {
                pw = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            List authors =  s.listAuthors();
            List names = new ArrayList();
            for (Author authors1:authors){
                names.add(authors1.getUsername());
            }
            if (names.contains(username)){
                pw.write("用户名呢已经存在");
            }else {
                pw.write("用户名可以使用");
            }
        }

你可能感兴趣的:(Ajax实现动态刷新页面(get))