Ajax之判斷用戶名是否存在

<pre>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
    <title>Document&lt/title>
    </head>

    <body>
   <h3>判斷用戶名是否存在</h3>
      <input type="text" name="username" id="username" value="">
    <br>
    <script src="ajax3.0-min.js"></script>
    <script>
    // 當input失去焦點的時候,驗證用戶名是否存在
    // 1.獲取對象
    var username = document.getElementById('username');

    // 2.失去焦點
    username.onblur = function() {
        // 獲取input的值(獲取用戶輸入的值)
        var value = this.value;

        // 將用戶輸入的內容發送到服務器,進行檢驗判斷是否存在存在
        Ajax().get('1.php?username=' + value, function(msg) {
            console.log(msg);
            if (msg == 1) {
                alert('該用戶已經被註冊');
            } else {
                alert('該用戶還沒有被註冊');
            }
        })
    }
    </script>
    </body>
    </html>
    </pre>
##1.PHP
    <?php

    // 服務器端:接收前端傳遞過來的用戶名,並且判斷是否存在
    $username = $_GET['username'];

    // 2.判斷是否存在
    // 定義數組,模擬數據倉庫,判斷接收的用戶名是否在數組中,在則證明存在,不在則說明用戶名還沒有註冊
    $arr = ['zhangsan','lisi','wangwu','zhaoliu'];

    // php頁面只能寫echo輸出
    if (in_array($username,$arr)) {
    echo 1;
    } else {
    echo 0;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章