一.Ajax-GET
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <label for="username">username</label> <input type="text" id="username" class="username" autofocus> <p id="contains"></p> <script> //获取输入框 var input=document.getElementById("username"); //获取p标签 var contains=document.getElementById("contains") //1.创建请求对象 var request=new XMLHttpRequest(); input.addEventListener('keypress',getcontains,false); function getcontains(event) { if(event.key==="Enter"){ switch (true) { //判断是否为空 case input.value.length === 0: contains.innerHTML = '<span style="color:red">ID为空!</span>'; return false; // 判断是否为整数 case isNaN(input.value): contains.innerHTML = '<span style="color:red">ID不是整数!</span>'; return false; default: //2.监听:成功回调 request.addEventListener('readystatechange',successCallback,false); //3.设置:请求参数 对数据进行编码处理 var data=encodeURIComponent(input.value); request.open('GET','1.php?user_id='+data,true); //4.发送:异步请求; request.send(null); } } } //成功的回调函数 function successCallback(event){ if(request.readyState===4){ contains.innerHTML=request.responseText; } } //为input添加事件每次重新输入input内容,清空contains内的提示或信息 input.addEventListener('input',clr,false); function clr(event){ contains.innerHTML=null; } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例
<?php $userId = isset($_GET['user_id']) ? $_GET['user_id'] : null; $userInfo = [ ['user_id' => 1, 'username' => '苍老师', 'gender' => '女', 'age' => 26], ['user_id' => 2, 'username' => '波老师', 'gender' => '女', 'age' => 23], ['user_id' => 3, 'username' => '黑老师', 'gender' => '男', 'age' => 33], ]; $res = ''; foreach ($userInfo as $user) { if ($user['user_id'] === intval($userId)) { $res .= $user['user_id'] . '---' . $user['username'] . '---' . $user['gender'] . '---' . $user['age']; } } echo empty($res) ? '<span style="color: red;">没有找到该用户名</span>' : $res; exit; ?>
点击 "运行实例" 按钮查看在线实例
二.一.Ajax-GET
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> </style> </head> <body> <h2>login</h2> <form action="" name="login"> <p> <label for="username">username:</label><br> <input type="text" name="username" id="username" placeholder="input username"> </p> <p> <label for="email">email:</label><br> <input type="text" name="email" id="email" placeholder="example@email.com"> </p> <p> <label for="password">password:</label><br> <input type="password" name="password" id="password"> </p> <p> <label for="remember">记住我:</label> <select name="remember" id="remember"> <option value="1" selected>1</option> <option value="7">7</option> <option value="30">30</option> </select> </p> <p> <button type="button" name="submit">提交</button> </p> </form> <script> var login=document.forms.namedItem("login"); var btn=login.submit; var request=new XMLHttpRequest(); login.username.addEventListener('blur',cck,false); login.email.addEventListener('blur',cck,false); login.password.addEventListener('blur',cck,false); function cck(event){ if(event.target.value.length===0){ if(event.target.nextElementSibling===null){ var contains=document.createElement("span"); contains.style.color="red"; switch(event.target.name){ case 'username': contains.innerText="username not allow empty"; break; case 'email': contains.innerText="email not allow empty"; break; case 'password': contains.innerText="password not allow empty"; break; default: contains.innerText="unknown error"; } event.target.parentNode.appendChild(contains); } //焦点聚集于错误输入框上 event.target.focus(); } } login.username.addEventListener('input',clr,false); login.email.addEventListener('input',clr,false); login.password.addEventListener('input',clr,false); function clr(event){ var contains=event.target.nextElementSibling; if(contains!==null){ contains.parentNode.removeChild(contains); } } btn.addEventListener('click',check,false); function check(event) { var username=login.username.value; var email=login.email.value; var password=login.password.value; var remember=login.remember.value; if (username.length === 0 || email.length === 0 || password.length === 0) { btn.removeEventListener('click',check,false); var blurEvent=new Event('blur'); login.username.dispatchEvent(blurEvent); return false; } // 2.监听:成功回调 request.addEventListener('readystatechange', successCallback, false); // 3.设置:请求参数 request.open('POST', 'php/check.php', true); //设置请求头部 request.setRequestHeader('content-type','application/x-www-form-urlencoded;charset=utf-8'); //4.发送:异步请求 var data = 'username='+username+'&email='+email+'&password='+password+'&remember='+remember; request.send(data); } function successCallback(event){ if(request.readyState===4){ console.log(request.responseText); } } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例
<?php session_start(); // 获取表单提交的数据 $username = $_POST['username']; $email = $_POST['email']; $password = sha1($_POST['password']); $remember = $_POST['remember']; // 为简化代码,不用数据表验证,使用硬编码,只验证邮箱与密码 if ($email === 'admin@php.cn' && $password === sha1('123456')) { $_SESSION['username'] = $username; $_SESSION['email'] = $email; echo json_encode(['status'=>1, 'message'=>'验证成功']); } else { echo json_encode(['status'=>0, 'message'=>'验证失败']); } exit;
点击 "运行实例" 按钮查看在线实例
总结:
1.Ajax-Get/Post请求基本步骤
(1)创建: 请求对象 var request = new XMLHttpRequest();
(2)监听: 成功回调
request.addEventListener('readstatechange', successCallback, false); function successCallback(ev) { if (request.readyState === 4) { console.log(request.responseText); } }
(3)设置: 请求参数
open(method,url,bool) method:请求类型 url:文件位置 bool:true异步/false同步
(4)发送: 请求
request.send();
其实GET与Post请求写法上并没有太大差距
POST与GET相比需要设置请求头以及发送请求时携带参数的写法稍微有点区别
2.当使用POST方法时候需要设置请求头部
setRequestHeader(header,value) header:头名称 value:规定头的值
request.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=utf-8');
3.Ajax的onreadystatechange事件
每当 readyState 改变时,就会触发 onreadystatechange 事件。
readyState 0: 请求未初始化 1: 服务器连接已建立 2: 请求已接收 3: 请求处理中 *4: 请求已完成,且响应已就绪
status 200: "OK" 404: 未找到页面
4.Ajax的服务端响应
如果需要获得来自服务器的响应,需要使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性。
responseText 获得字符串形式的响应数据
responseXML 获得XML形式的响应数据