原生的ajax 異步交互過程

html表單

<body>
    <div id="showinfo">1</div>
   <form id="form">
    用戶名:<input type="text" name="name" id="name">
    <br/>
    密 碼: <input type="password" name="psd" id="psd">
    <input type="submit" value="提交" id="btn">
   </form>
</body>

js中ajax代碼 (簡單的信息驗證)

<script type="text/javascript">
    window.onload = function () {//頁面加載
        var btn = document.getElementById('btn');
        btn.onclick = function () {//按鈕點擊時,發生時間
            var name = document.getElementById('name').value;
            var psd = document.getElementById('psd').value;
            var xhr = null;
            if (window.XMLHttpRequest) {//普通瀏覽器可以識別XMLHttpRequest對象
                xhr = new XMLHttpRequest();
            }
            else {//沒有xhlhttprequest對象的話,創建IE5,6自己的對象ActiveXObject
                xhr = new ActiveXObject("microsoft.XMLHTTP");
            }
            var url = './check.php?username=' + name + "&password=" + psd;
            xhr.open('get', url, true);//準備執行的內容
            xhr.onreadystatechange = function () {//,當send函數執行完成後,執行的回調函數
                if (xhr.readyState == 4) {//這件事已經完成
                    if (xhr.status == 200) {//這件事完成的情況
                        //alert(2);
                        var data = xhr.responseText;//從後臺返回的數據
                        if (data == 1) {
                            document.getElementById('showinfo').innerHTML = '信息失敗';
                        } else if (data == 2) {
                            document.getElementById('showinfo').innerHTML = '信息正確';

                        }
                    }
                }
            }
            xhr.send(null);
        }
    }
</script>

php頁面 後臺數據的處理

<?php
$username = $_GET['username'];//通過get請求方式,接收前臺的數據
$psd = $_GET['password'];
if($username == 'admin' && $psd == '123'){//admin和123這裏是靜態的數據
    echo 2;//返回的信息,ajax中xhr.responseText;返回的data是1 or 2
}
else{
    echo 1;
}
?>

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