什麼是AJAX
Asynchronous JavaScript And Xml
異步的 JS 和 Xml
通過js異步的向伺服器發送請求并接受響應資料
同步通路:
當用戶端向伺服器發送請求時 伺服器在處理的過程中浏覽器隻能等待
異步通路:
當用戶端向伺服器發送請求時 伺服器在處理的過程中 用戶端可以做其他操作
不需要一直等待
AJAX優點:
異步通路
局部重新整理
使用場合:
搜尋建議
表單驗證
前後端完全分離
AJAX核心對象 異步核心對象(XMLHttprequest):
什麼是XMLHTTPRequest
代替浏覽器向伺服器發送異步請求并接受響應的 “異步對象”
是由js來提供的
建立異步對象
主流的異步對象是XMLHTTPRequest類型的
并且主流浏覽器(IE+ Chrome Firefox Safari Opera)都支援
低版本浏覽器中(IE6以下)就不支援XMLHTTPRequest
需要使用ActiveXObject() 來建立異步對象
1.AJAX
1.建立 xhr
/**
* common.js
*/
function createXhr(){
if(window.XMLHttpRequest)
return new XMLHttpRequest();
else
return new ActiveXObject('Microsoft.XMLHTTP');
}
@app.route('/02-get')
def get_views():
return render_template('02-get.html')
2.xhr 的成員
1.方法 - open()
作用:建立請求
文法:open(method,url,asyn)
method:請求方式,取值'get' 或 'post'
url:請求位址,字元串
asyn:是否采用異步的方式
true:異步
false:同步
ex:
xhr.open('get','/server',true);
2.屬性 - readyState
作用:請求狀态,通過不同的請求狀态來表示xhr與伺服器的互動情況
由0-4共5個值來表示5個不同的狀态
0 :請求尚未初始化
1 :已經與伺服器建立連接配接
2 :伺服器端已接收請求
3 :請求正在進行中
4 :響應已經完成
3.屬性 - status
作用:伺服器端的響應狀态碼
200 :表示伺服器正确處理所有的請求以及給出響應
404 :請求資源不存在
500 :伺服器内部錯誤
... ...
4.事件 - onreadystatechange
作用:每當xhr的readyState發生改變的時候都要觸發的操作 - 回調函數
隻有當readyState的值為4并且status的值為200的時候,才可以正常的去接收響應資料
5.屬性 - responseText
作用:響應資料
6.方法 - send()
作用:通知xhr向伺服器端發送請求
文法:send(body)
get請求:body的值為null
send(null)
post請求:此處為要送出的資料
send("請求資料")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="send_ajax()">發送AJAX請求</button>
<p id="show"></p>
<script src="/static/js/common.js"></script>
<script>
function send_ajax(){
//1.建立xhr
var xhr = createXhr();
//2.建立請求
// xhr.open(method,url,asyn)
xhr.open('get','/02-server',true);
//3.設定回調函數(判斷狀态接收響應資料)
//xhr.onreadystatechange = function(){}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
//xhr的自身狀态是4并且伺服器的狀态是200就可以接收響應資料
document.getElementById('show').innerHTML = xhr.responseText;
}
}
//4.發送請求
xhr.send(null);
}
</script>
</body>
</html>
3.AJAX的操作步驟
1.GET請求
1.建立 xhr 對象
2.建立請求 - open()
3.設定回調函數 - onreadystatechange 判斷狀态并接收響應資料
4.發送請求 - send()
請求參數:
推薦:請求位址後拼QueryString
xhr.open('get','/02-server?key=value&key=value',true)
2.POST請求
4.設定請求消息頭 - Content-Type
5.發送請求 - send()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/static/js/common.js"></script>
<script src="/static/js/jquery-1.11.3.js"></script>
</head>
<body>
姓名:<input type="text" id="uname">
<button id="btnSend">發送AJAX請求</button>
<p id="show"></p>
<script>
$(function(){
$("#btnSend").click(function(){
//1.建立xhr
var xhr = createXhr();
//2.建立請求
var url = "/03-server?uname="+$("#uname").val();
xhr.open('get',url,true);
//3.設定回調函數
xhr.onreadystatechange = function(){
if(xhr.readyState==4&&xhr.status==200){
$("#show").html(xhr.responseText);
}
}
//4.發送請求
xhr.send(null);
});
});
</script>
</body>
</html>