用post進行Ajax傳輸步驟

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>初識Ajax開發</title>
    <script type="text/javascript">
    window.onload = function(){
        var btn = document.getElementById('btn');
        btn.onclick = function(){
            var uname = document.getElementById('username').value;
            var pw = document.getElementById('password').value;

            // 1、創建XMLHttpRequest對象
            var xhr = null;
            if(window.XMLHttpRequest){
                xhr = new XMLHttpRequest();//標準
            }else{
                xhr = new ActiveXObject("Microsoft");//IE6
            }
            // 2、準備發送
            /*
            參數一:請求方式(get獲取數據;post提交數據)
            參數二:請求地址
            參數三:同步或者異步標誌位,默認是true表示異步,false表示同步
            
            post請求參數通過send傳遞,不需要通過encodeURI()轉碼
            必須設置請求頭信息
            */
            var param = 'username='+uname+'&password='+pw;
            xhr.open('post','04post.php',false);
            // 3、執行發送動作
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xhr.send(param);//post請求參數在這裏傳遞,並且不需要轉碼
            // 4、指定回調函數
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4){
                    if(xhr.status == 200){
                        alert(xhr.responseText);
                    }
                }
            }
            
        }
    }
    </script>
</head>

<body>
    <form>
        用戶名:
        <input type="text" name="username" id="username"><span id="info"></span>
        <br> 密碼:
        <input type="text" name="password" id="password">
        <input type="button" value="登錄" id="btn">
    </form>
</body>

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