苇谰尖筷补才啪默坞少捅醇盆
demo3.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>3.Ajax入门</title> </head> <body> <form action="api/check.php" method="post"> <fieldset id=""> <legend>用户登录</legend> <p> <label for="email">邮箱</label> <input type="text"name="email" id="email" /> </p> <p> <label for="password">密码</label> <input type="password" name="password" id="password"/> </p> <p> <button>登录</button> <span id="tips" style="font-size:1.2em;font-weight: bolder;color:red"></span> </p> </fieldset> </form> </body> </html> <script type="text/javascript"> var btn=document.getElementsByTagName('button')[0] btn.onclick=function(){ alert('登录成功') return false } </script>
执行:
目录结构:
demo3.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>3.Ajax入门</title> </head> <body> <form action="api/check.php" method="post"> <fieldset> <legend>用户登录</legend> <p> <label for="email">邮箱:</label> <input type="email" name="email" id="email"> </p> <p> <label for="password">邮箱:</label> <input type="password" name="password" id="password"> </p> <p><button>登录</button> <span id="tips" style="font-size:1.2em;font-weight: bolder;color:red"></span></p> <!-- 取消原生提交动作 --> <!-- <p><button type="button">登录</button></p> --> </fieldset> </form> </body> </html> <script type="text/javascript"> var btn = document.getElementsByTagName('button')[0] btn.onclick = function () { //获取用户提交的数据 var email = document.getElementById('email').value var password = document.getElementById('password').value //将用户数据组装成查询字符串 var data = 'email='+email+'&password='+password //1.创建xhr对象 var xhr = new XMLHttpRequest() //2.事件监听 xhr.onreadystatechange = function (){ //5.设置回调函数 if (xhr.readyState == 4 && xhr.status == 200) { //dom操作 var tips = document.getElementById('tips') if (xhr.responseText == '1') { tips.innerHTML = '登录成功,正在跳转中...' setTimeout(function(){ location.href = 'api/index.php' },2000) } else { tips.innerHTML = '邮箱或密码错误,请重新输入' document.getElementById('email').focus() setTimeout("tips.innerHTML = ''",2000) } } } //3.建立连接 xhr.open('POST','api/user.php?m=login',true) //4.发送数据 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded') xhr.send(data) return false //禁止原按钮的提交行为 } </script>
user.php
<?php if ($_GET['m'] == 'login') { if ($_POST['email'] == 'admin' && $_POST['password'] == '123456'){ echo '1'; } else { echo '0'; } }
index.php
<?php echo '<h1 style="color:red">登录成功</h1>';
执行,不输入数据直接提交:
输入admin 123456
删既硷烙景瓜涎校当甘鄙盲凑