1. 程式人生 > >Ajax實現動態重新整理頁面(get)

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<Author> authors =  s.listAuthors();
            List names = new ArrayList();
            for (Author authors1:authors){
                names.add(authors1.getUsername());
            }
            if (names.contains(username)){
                pw.write("<font color='red'>使用者名稱呢已經存在</font>");
            }else {
                pw.write("<font color='green'>使用者名稱可以使用</font>");
            }
        }