<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>2.AJAX异步提交</title> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> </head> <body> <form action="check.php" method="POST" name="login"> <p> <label for="email">邮 箱</label> <input type="email" name="email" id="email"> <span style="color:red;" id="msg">*</span> </p> <p> <label for="pwd">密 码</label> <input type="password" name="pwd" id="pwd"> <span style="color:red;" id="msg">*</span> </p> <button>登录</button> </form> <button onclick="add()">JQ ajax提交</button> </body> </html> <script> // 获取form表单对象与控件 var login = document.forms['login']; var email = document.getElementsByName('email')[0]; var pwd = document.getElementsByName('pwd')[0]; var btn = document.getElementsByTagName('button')[0]; var msg = document.getElementById('msg'); // 提交时执行邮箱和密码判断 login.onsubmit = function(){ if(login.email.value.length === 0){ alert('请输入邮箱'); return false; }else if(login.pwd.value.length === 0){ alert('请输入密码'); return false; } } // 验证邮箱 email.onblur = function(){ // 1.创建ajax请求对象 var request = new XMLHttpRequest(); // 2.请求成功的回调处理 request.onreadystatechange = function(){ // 当请求完成④并成功获取到数据(200) if(this.readyState === 4 && this.status === 200){ msg.innerHTML = this.responseText; console.log(this.responseText); } } // 3.设置请求参数 request.open('POST','check.php',true); // 4.POST请求需要设置请求头信息 request.setRequestHeader('content-type','application/x-www-form-urlencoded'); // 5.发送请求 request.send('email=' + email.value + '&pwd=' + pwd.value); } // 用户修改信息时,清空msg email.oninput = function(){ msg.innerHTML = ''; } //jQuery ajax提交 // function add(){ // $.post('check.php',$('form').serialize(),function(res){ // if(res.code === 1){ // console.log(res.msg); // return false; // } // },'json'); // } </script>
点击 "运行实例" 按钮查看在线实例
<?php $data['email'] = $_POST['email']; $data['pwd'] = md5($_POST['pwd']); echo '<pre>'; print_r($data); exit(json_encode(array('code'=>1,'msg'=>$data))); ?>
点击 "运行实例" 按钮查看在线实例