web 前端 - Ajax 基础技术
Ajax 是浏览器提供一套的 API, 用于向服务器发出请求, 接受服务端返回的响应, 通过 JavaScript 调用, 实现通过代码控制请求与响应, 实现网络编程.
Ajax 发送请求:
- <!DOCTYPE html>
- <HTML lang="en">
- <head>
- <meat charset="UTF-8">
- <title>
- Ajax
- </title>
- </head>
- <body>
- <script>
- // Ajax 是一套 API 核心提供的类型:
- var xhr = new XMLHttpRequest();
- xhr.open();
- xhr.send();
- xhr.onreadystatechange = function() {
- if (this.readyState != 4) return
- // 获取响应的内容
- console.log(this.responseText);
- }
- </script>
- </body>
- </HTML>
- <script>
- var xhr = new XMLHttpRequest()
- console.log(xhr.readyState);
- xhr.open('GET', 'xxx.php')
- console.log(xhr.readyState); // 1 初始化 请求代理对象
- xhr.send()
- console.log(xhr.readyState); // 1
- xhr.addEventListener('readystatechange', function(){
- // if(this.readyState != 4) return
- // console.log(this.readyState);
- })
- // Ajax 创建一个 XMLHttpRequest 类型的对象, 相当于打开一个浏览器
- var xhr = new XMLHttpRequest()
- // 打开一个网址之间的连接
- xhr.open('GET','##.php')
- // 通过连接发送一次请求
- xhr.send(null)
- // 指定 xhr 状态变化事件处理函数
- xhr.onreadystatechange = function() {
- // 通过 xhr 的 readyState 判断请求的响应
- if(this.readyState === 4){
- console.log(this);
- }
- }
- <script>
- var xhr = new XMLHttpRequest();
- xhr.open('GET', 'xxx.php')
- xhr.send(null)
- xhr.onload=function(){
- console.log(this.readyState)
- console.log(this.responseText)
- }
- </script>
http 协议:
- <script>
- var xhr = new XMLHttpRequest()
- xhr.open('GET', '/##.php') // 设置请求行
- // xhr.setRequestHeader('HH', 'DA') // 设置一个请求头
- xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
- xhr.send('key=value&key1=value1') // 设置请求体
- <body>
- <form action="##.php" method="post">
- <input type="text" name="name" id="">
- <button > 提交 </button>
- </form>
- </body>
- // http
- // 设置请求报文的请求行
- xhr.open('GET', './###.php')
- // 设置请求头
- xhr.setRequestHeader('Accept', 'text/plain')
- // 设置请求体
- xhr.send(null)
- xhr.onreadystateChange = function() {
- if(this.readyState === 4) {
- // 获取响应状态码
- console.log(this.status)
- // 获取响应状态描述
- console.log(this.statusText)
- // 获取响应头信息
- // 获取指定响应头
- console.log(this.getResponseHeader('Content-Type'))
- // 获取全部响应头
- console.log(this.getAllResponseHeader())
- // 获取响应体
- // 获取响应文本形式
- console.log(this.responseText)
- // 获取 xml 形式
- console.log(this.responseXML)
- }
- }
进行初始化, 建立连接, 接收响应, 响应体加载, 加载成功!
- // get 请求
- var xhr = new XMLHttpRequest()
- xhr.open('GET', '.##.php?id=1')
- // 一般 get 请求无需设置响应体
- xhr.send(null);
- xhr.onreadystatechange = function(){
- if(this.readyState === 4) {
- console.log(this.responseText);
- }
- }
- // post
- if(empty($_GE['id])) {
- $JSON = json_encode($data);
- echo $JSON;
- }else{
- foreach($data as $item) {
- if($item['id'] != $_GET['id'] continue;
- $JSON = json_encode($data);
- echo $JSON;
- }
- }
异步的 JavaScript 和 xml
Ajax = Asynchronous JavaScript and xml
用于创建快速动态网页的技术
XMLHttpRequest 对象
- var xhr;
- if (Windows.XMLHttpRequest){
- xhr=new XMLHttpRequest();
- }
- else{
- xhr=new ActiveXObject("Microsoft.XMLHTTP");
- }
向服务器发送请求
- xmlhttp.open("GET","123.txt",true);
- xmlhttp.send();
请求类型, 为 get 和 post,url 文件在服务器上的位置, true 异步和 false 同步.
- xhr.open("POST","###.asp",true);
- xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
- xhr.send("name=da&age=12");
onreadystatechange 事件
XMLHttpRequest 的状态信息, 从 0 到 4 变化, 0 为请求未初始化, 1 为建立连接成功, 2 为请求已接收, 3 为请求处理中, 4 为请求完成.
- xhr.onreadystatechange=function() {
- if (xhr.readyState==4 && xhr.status==200) {
- }
- }
- <ul id="list"></ul>
- var listElement = document.getElementById('list');
- var xhr = new XMLHttpRequest();
- xhr.open('GET', '###.php?id=2');
- xhr.send(null)
- xhr.onreadystatechange = function() {
- if(this.readyState != 4) return
- // console.log(this.responseText)
- var data = JSON.parse(this.responseText)
- for(var i = 0; i<data.length; i++) {
- var liElement = document.createElement('li');
- liElement.innerHTML = data[i].name;
- listElement.appendChild(liElement);
- }
- }
- xhr.onreadystatechange = function() {
- if(this.readyState != 4) return
- var data = JSON.parse(this.responseText)
- for(var i = 0; i<data.length; i++){
- var liElement = document.createElement('li')
- liElement.innerHTML = data[i].name;
- liElement.id=data[i].id
- listElement.appendChild(liElement);
- liElement.addEventListener('click', function() {
- var xhr1 = new XMLHttpRequest();
- xhr1.open('GET', '###.php?id=' + this.id)
- xhr1.send()
- xhr1.onreadystatechange = function() {
- if(this.readyState != 4) return
- var obj = JSON.parse(this.responseText)
- alert(obj.age)
- }
- }
- }
- }
onreadystatechange 事件
readyState 返回当前请求的状态
responseBody 将回应信息文体
status 返回当前请求的状态码
statusText 返回当前请求的响应的状态
abort 取消当前请求
getAllResponseHeaders 获取响应指定的 http 头
open 创建一个新的 http 请求
send 发送请求到 http 服务器并接收回应
setRequestHeader 指定请求头
效果
- <?PHP
- if(empty($_POST['username']) || empty($_POST['password'])) {
- exit('请输入用户名和密码');
- }
- // 校验
- $username = $_POST['username'];
- $password = $_POST['password'];
- if($username === 'admin' && $password === '123') {
- exit('成功');
- }
- exit('失败');
- ?>
- var btn = document.getElementById('btn');
- // 获取元素
- var txtUsername = document.getElementById('username');
- var textPassword = document.getElementById('password');
- btn.onclick = function() {
- var username = txtUsername.value;
- var password = txtPassword.value;
- var xhr = new XMLHttpRequest();
- xhr.open('POST', '##.php');
- xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
- // xhr.send('username=' + username + '&password=' + password)
- xhr.send(`username=${username}&password=${password}`);
- // 界面
- xhr.onreadystatechange = function() {
- if(this.readyState != 4) return
- console.log(this.responseText);
- }
- }
- // jQuery 中的 Ajax
- $.Ajax({
- type: 'GET',
- url: "###.php?id="+$('#id').val(),
- dataType: "json"
- success: function(data){
- $("jq").HTML();
- }else{
- $("jq").HTML();
- },
- error: function(jq) {
- alert();
- }
- })
- $.Ajax({
- type: "POST",
- url: "ajax.php",
- dataType: "json",
- data: {"username": "admin","password": 123},
- success: function(msg) {
- console.log(msg)
- },
- error: function() {
- console.log("error")
- }
- })
- function creathttprequest(){
- if(Windows.XMLHttpRequest)
- var xml=new XMLHttpRequest();
- else
- var xml=ActiveXObject("Miscrosoft.XMLHTTP");
- return xml;
- }
- function addAjax() {
- var xml = createhttprequest();
- xml.open("POST","123.php",false);
- xml.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
- xml.send(url);
- if( xml.readyState == 4 && xml.status == 200 ) {
- alert(xml.responseText);
- }
- }
响应数据
- <?PHP
- header('Content-Type: application/xml');
- ?>
- <?xml version="1.0" encoding="utf-8"?>
- <person>
- <name>dashu</name>
- <age>16</age>
- <gender > 男 </gender>
- </person>
- <script>
- var xhr = new XMLHttpRequest()
- xhr.open('GET', '###.php')
- xhr.send()
- xhr.onreadystatechange = function() {
- if(this.readyState != 4) return
- // console.log(this.responseXML)
- // console.log(this.responseXML.documentElement.getElementsByTagName('name')[0])
- // console.log(this.responseXML.documentElement.children[0].innerHTML)
- }
如何解析服务端的数据:
- <table>
- <tbody id="content"></tbody>
- </table>
- <script>
- var xhr = new XMLHttpRequest()
- xhr.open('GET', '###.php')
- xhr.send()
- xhr.onreadystatechange = function() {
- if(this.readyState != 4) return
- var res = JSON.parse(this.responseText);
- var data = res.data
- for(var i = 0; i<data.length; i++) {
- var tr = document.createElement("tr");
- var td = document.createElement("td");
- td.innerHTML = data[i].id;
- }
- }
- </script>
兼容:
var xhr = Windows.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
模板:
https//aui.GitHub.io/art-template/
面试手写:
- var xhr = new XMLHttpRequest();
- xhr.open('GET', '###.php');
- xhr.send(null);
- xhr.onreadystatechange = function() {
- if(this.readyState === 4){
- console.log(this);
- }
- }
实例:
- <script>
- function add(){
- var xhr;
- if (Windows.XMLHttpRequest){
- xhr=new XMLHttpRequest();
- }else{
- xhr=new ActiveXObject("Microsoft.XMLHTTP");
- }
- xhr.onreadystatechange=function(){
- if (xhr.readyState==4 && xhr.status==200)
- {
- document.getElementById("div").innerHTML=xhr.responseText;
- }
- }
- xmlhttp.open("GET","/info.txt",true);
- xmlhttp.send();
- }
- </script>
效果
实例:
- <script>
- function change(str){
- if(str == ""){
- document.getElementById("txt").innerHTML="";
- return;
- }
- if(Windows.XMLHttpRequest){
- xhr=new XMLHttpRequest();
- }else{
- xhr=new ActiveXObject("Microsoft.XMLHTTP");
- }
- xhr.onreadystatechange=function(){
- if (xhr.readyState==4 && xhr.status==200){
- document.getElementById("txt").innerHTML=xhr.responseText;
- }
- }
- xhr.open('GET','###.php?id=' + str, true);
- xhr.send();
- }
- </script>
- <form>
- <select name="users" onchange="change(this.value">
- <option value=""></option>
- <option value="1"></option>
- <option value="2"></option>
- </select>
- </form>
- <div id="txt"></div>
- //PHP
- $id = isset($_GET["id"]) ? intval($_GET["id"]) : '';
- $con = mysqli_connect('localhost','root','123456');
- if (!$con)
- {
- die('连接失败:' . mysqli_error($con));
- }
- // 选择数据库
- mysqli_select_db($con,"test");
- // 设置编码
- mysqli_set_charset($con, "utf8");
- $sql="SELECT * FROM Websites WHERE id ='".$id."'";
- $result = mysqli_query($con,$sql);
结言
好了, 欢迎在留言区留言, 与大家分享你的经验和心得.
感谢你学习今天的内容, 如果你觉得这篇文章对你有帮助的话, 也欢迎把它分享给更多的朋友, 感谢.
来源: http://www.jianshu.com/p/596a781b0b16