摘要: <!DOCTYPE html> <html> <head> <title>Ajax原理實(shí)線</title> <meta charset="utf-8"> </head> <body> <form accept-charset="
<!DOCTYPE html> <html> <head> <title>Ajax原理實(shí)線</title> <meta charset="utf-8"> </head> <body> <form accept-charset="utf-8"> <label>郵箱:</label> <input type="email" name="email" id="email"><br><br> <label>密碼</label> <input type="password" name="password" placeholder="" id="password"><br> <input type="button" name="" value="提交" id='btn'><br> </form> <script type="text/javascript"> // 1.創(chuàng)建Ajax對(duì)象 // let email = document.getElementById("email"); // let e = email.value // let password = ; // console.log(password) let btn = document.getElementById("btn"); btn.onclick= function(){ let xhr = new XMLHttpRequest(); // 2.啟動(dòng)監(jiān)聽(tīng) xhr.onreadystatechange = function () { if (xhr.readyState=== 4 ){ //請(qǐng)求成功需要操作的內(nèi)容 if (xhr.status===200) { // 響應(yīng)成功 let ps = document.createElement('p'); let enjson = JSON.parse(xhr.responseText); //JSON.parse()方法可以將服務(wù)器發(fā)送過(guò)來(lái)的JSON格式解析成JS的對(duì)象 if (enjson['status']===1) { ps.innerHTML=enjson['msg']; }else if (enjson['status']===0){ ps.innerHTML=enjson['msg']; } document.body.appendChild(ps); setTimeout(function(){ //計(jì)時(shí)器 location.href='admin.php'; }, 2000) }else { // 響應(yīng)失敗 } }else{ // 如果請(qǐng)求在繼續(xù)那么可以輸出一張圖片 } } let json = { email:document.getElementById("email").value, password:document.getElementById("password").value } json = JSON.stringify(json); //將JS對(duì)象轉(zhuǎn)為字符串 // 3.發(fā)送請(qǐng)求 xhr.open('post', 'check.php', true); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //POST要修改請(qǐng)求頭 xhr.send("data="+json);//手動(dòng)添加一個(gè)鍵,拼接json變量的值,發(fā)送到服務(wù)器 } </script> </body> </html>
批改老師:查無(wú)此人批改時(shí)間:2019-05-05 09:50:06
老師總結(jié):完成的不錯(cuò)。ajax功能很強(qiáng)大,用到的也比較多。繼續(xù)加油。