亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

ajax登陸表單提交

原創(chuàng) 2019-05-13 13:42:12 232
摘要:<!DOCTYPE html><html><head>    <meta charset="UTF-8">    <title>Ajax實(shí)戰(zhàn):表單驗(yàn)證</title></head><body><h3>用戶登錄</h3>&

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Ajax實(shí)戰(zhàn):表單驗(yàn)證</title>

</head>

<body>

<h3>用戶登錄</h3>

<form>

    <p>郵箱: <input type="email" name="email"></p>

    <p>密碼: <input type="password" name="password"></p>

    <p><button type="button">提交</button></p>

</form>

<script>

    let btn = document.getElementsByTagName('button')[0];

    btn.onclick = function () {

        //1.創(chuàng)建xhr對(duì)象

        let xhr = new XMLHttpRequest();


        //2.監(jiān)聽響應(yīng)狀態(tài)

        xhr.onreadystatechange = function(){

            if (xhr.readyState === 4) { // 準(zhǔn)備就緒

                // 判斷響應(yīng)結(jié)果:

                if (xhr.status === 200) {

                    // 響應(yīng)成功,通過xhr對(duì)象的responseText屬性可以獲取響應(yīng)的文本,此時(shí)是html文檔內(nèi)容

                    let p = document.createElement('p');  //創(chuàng)建新元素放返回的內(nèi)容

                    p.style.color = 'red';


                    let json = JSON.parse(xhr.responseText);

                    if (json.status === 1) {

                        p.innerHTML = json.msg;


                    } else if (json.status == 0) {

                        p.innerHTML = json.msg;

                    }

                     // 將響應(yīng)文本添加到新元素上

                    document.forms[0].appendChild(p); // 將新元素插入到當(dāng)前頁面中

                    btn.disabled = true;

                    setTimeout(function(){

                        document.forms[0].removeChild(p);

                        btn.disabled = false;

                        if (json.status == 1) {

                            location.href = 'admin.php';

                        }

                        },2000);

                } else {

                    // 響應(yīng)失敗,并根據(jù)響應(yīng)碼判斷失敗原因

                    alert('響應(yīng)失敗'+xhr.status);

                }

            } else {

                // http請(qǐng)求仍在繼續(xù),這里可以顯示一個(gè)一直轉(zhuǎn)來轉(zhuǎn)去的圖片

            }


        }


        //3.設(shè)置請(qǐng)求參數(shù)

        xhr.open('post','inc/check.php',true);


        //4. 設(shè)置頭信息,將內(nèi)容類型設(shè)置為表單提交方式

        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');


        //4.發(fā)送請(qǐng)求

        let data = {

          email:  document.getElementsByName('email')[0].value,

          password:  document.getElementsByName('password')[0].value

        };

        // data = 'email='+data.email+'&password='+data.password;

        let data_json=JSON.stringify(data);

        xhr.send('data='+data_json);

    }

</script>

</body>

</html>


批改老師:查無此人批改時(shí)間:2019-05-14 09:33:46
老師總結(jié):完成的不錯(cuò)。ajax功能很強(qiáng)大,也很簡(jiǎn)單。多練習(xí),之后用到很多。繼續(xù)加油。

發(fā)布手記

熱門詞條