ajax異步校驗用戶名

AJAX異步校驗用戶名

AJAX是一種在無需重新加載整個網頁的情況下,能夠更新部分網頁的技術。
在web開發中,經常會遇到需要發送局部請求,比如說驗證用戶名是否存在,獲取手機驗證碼等,
單純的驗證用戶名是否存在沒有必要提交整個頁面,這樣有助於提升響應速度。


這裏寫圖片描述


前端代碼

    <script type="text/javascript">
        function getXhr() {
            var xhr = null;
            if(window.XMLHttpRequest){
                xhr = new XMLHttpRequest();
            }else {
                xhr = new ActiveXObject("Microsoft.XMLHttp");
            }
            return xhr;
        }
        function checkNameUnique() {
            var xhr = getXhr();
            xhr.onreadystatechange = function () {
                if(xhr.readyState == 4&&xhr.status == 200){
                    document.getElementById("username_btn").value =xhr.responseText;
                }
            };
            xhr.open("post","/checkNameUnique",true);
            xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
            document.getElementById("username_btn").value = "正在驗證";
            var uname = document.getElementById("username_register").value;
            var username = (uname=='用戶名')?'':uname;
            xhr.send("uname="+username);
        }
    <script>
     ......
    <h2>註冊  </h2>
    <form action="/register" method="post">
        <div>
            <input class="username_register" name="username_register" id="username_register" value="用戶名" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = '用戶名';}">
            <input class="btn" type="button" id="username_btn" value="驗證用戶名" onclick="checkNameUnique()"/>
        </div>
        <input classs="tel" name="usrtel" value="手機號" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = '手機號';}">
        <div>
            <input class="content3" name="code" value="驗證碼" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = '驗證碼';}"/>
            <button class="btn" onclick="false;" >獲取驗證碼</button>
        </div>
        <input class="pwd_register" name="psw_register" value="密碼" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = '密碼';}">
        <input type="submit" class="register" value="註冊">
    </form>

後端代碼

@RequestMapping(path = {"/checkNameUnique"},method = {RequestMethod.POST})
    @ResponseBody
    private String checkNameUnique(@RequestParam("uname") String username){
        return userService.checkUsername(username);
    }

調試的時候出現的問題

在調試的時候曾把xhr.open和xhr.setRequestHeader這兩個函數順序寫反了,效果一直就出不來。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章