Correction status:qualified
Teacher's comments:Ajax的本质是异步, 但异步执行的不一定都是Ajax, Ajax只是实现异步编程的一种手段罢了
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax验证</title> </head> <body> <h1>用户注册</h1> <form action="" name="register"> <p> <label for="username">用户名:</label> <input type="text" name="username" id="username"> </p> <p> <label for="password">密码:</label> <input type="password" name="password" id="password"> </p> <button type="button" name="submit">注册</button> </form> <script> var register=document.forms.namedItem('register'); var input =document.getElementById('username'); var password =document.getElementById('password'); var btn = login.submit; var request= new XMLHttpRequest(); input.addEventListener('focus', function (ev) { ev.target.style.backgroundColor = 'lightgreen'; }, false); input.addEventListener('blur', function (ev) { return ev.target.value.length === 0 ? alert('不能为空') : false; }, false); password.addEventListener('focus',function(ev){ ev.target.style.backgroundColor = 'lightgreen'; }, false); password.addEventListener('blur', function (ev) { return ev.target.value.length === 0 ? alert('不能为空') : false; }, false); request.addEventListener('readstatechange', successCallback, false); function successCallback(ev) { if (request.readyState === 4) { console.log(request.responseText); } } btn.addEventListener('click', check, false); function check(ev) { var username = login.username.value; var password = login.password.value; if (username.length === 0 || password.length === 0) { ev.target.removeEventListener('click', check, false); var blurEvent = new Event('blur'); login.username.dispatchEvent(blurEvent); return false; } var data = 'username='+username+'&password='+password+'; request.addEventListener('readystatechange', successCallback, false); request.open('POST', 'php/check.php', true); request.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=utf-8'); request.send(data); } function successCallback(ev) { // console.log(ev.target); if (request.readyState === 4) { var obj = JSON.parse(request.responseText); var tips = document.createElement('span'); var url = ''; switch (obj.status) { case 1: tips.style.color = 'green'; tips.innerText = obj.message+',正在跳转...'; url = 'php/admin.php'; break; case 0: tips.style.color = 'red'; tips.innerText = obj.message; url = 'demo1.html'; // 也可以重新加载本页面 break; default: console.log('未知错误'); break; } btn.parentNode.appendChild(tips); setTimeout(function () { location.href = url; }, 3000); } } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例