其中在Ajax中最重要的就是XMLHttpRequest對象
// ajax
let xhr = new XMLHttpRequest(); // 創(chuàng)建xhr對象
// 第一個方法:open(get | post等, "exam.php", false) 參數(shù)為請求類型,請求url,是否異步的boolean
xhr.open("get","exam.php", false); // 調(diào)用該方法并不是真正的請求幸海,而是請求一個請求以備發(fā)送
// 發(fā)送真正的請求馅扣,接收一個參數(shù),即作為請求主體要發(fā)送的數(shù)據(jù)丘薛,不發(fā)送數(shù)據(jù)時必須傳遞null,因為對于某些瀏覽器來說該參數(shù)是必須的
xhr.send(null)
// 檢驗響應的狀態(tài)--->針對同步
if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
let data = xhr.responseText;
}else{
console.log(xhr.status);
}
// 異步方案
xhr.onreadystatechange = function(){
// xhr.readyStatus表示請求/響應過程的當前活動階段
// 0 未初始化,還沒調(diào)用open()
// 1 啟動缅糟,已調(diào)用open()方法但未調(diào)用send()
// 2 發(fā)送魔吐, 已調(diào)用send()方法,但未收到響應
// 3 接收综慎,已接收到部分響應數(shù)據(jù)
// 4 完成涣仿,已接受到全部響應數(shù)據(jù)
if(xhr.readyStatus == 4){
if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
let data = xhr.responseText;
}else{
console.log(xhr.status);
}
}
}
xhr.open("get","exam.php", false);
xhr.send(null);
// 在接收到響應之前還可以取消異步請求
xhr.abort() // 在停止請求之后還應該進行解引用操作,防止內(nèi)存堆積
// 設置http請求頭示惊,必須放在open和send中間
xhr.open("get","exam.php", false);
xhr.setRequestHeader("accept", "application/json; charset=utf-8")
xhr.send(null);
// 獲取響應頭信息
xhr.getResponseheader("accept");
xhr.getAllResponseHeaders();
// get請求:向現(xiàn)有url中添加查詢字符串
function addUrlParam(url, name, value){
url += (url.indexOf("?") == -1 ? "?" : "&");
url += encodeURIComponent(name) + "=" + encodeURIComponent(value);
}
// post請求:模擬表單提交
xhr.open("get","exam.php", false);
// 設置提交時的內(nèi)容類型
xhr.setRequestHeader("content-Type", "application/x-www-form-urlencoded")
// 假設表單form對象已獲取
xhr.send(serialize(form));
// XHR2級 -- formData --序列化表單以及創(chuàng)建和表單格式相同的數(shù)據(jù)(用于通過xhr傳輸)
let data = new FormData();
data.append(key,value);
// 也就可以用表單元素的數(shù)據(jù)預先填入數(shù)據(jù)
let data = new FormData(document.forms[0]);
//使用FormData的好處在于不必明確地在xhr上設置請求頭部
xhr.send(new FormData(form));
// 進度事件
loadStart/progress/error/abort/load
/*
跨域資源共享CORS
核心思想: 使用自定義的http頭部讓瀏覽器和服務器進行溝通好港,從而決定請求是成功還是失敗
原理:
1.請求頭指定源:Origin: http://www.baidu.com
2.如果服務器認為這個請求可以接受,就在Access-Control-Allow-Origin頭部回發(fā)相同的源信息
Access-Control-Allow-Origin:http://www.baidu.com
(如果是公共資源米罚,可以回發(fā)“*”)
3.如果沒有這個頭部钧汹,或者有這個頭部但是源信息不匹配,瀏覽器就會駁回請求
*/
// 主流瀏覽器對cros的實現(xiàn)方式: 在url中使用絕對路徑录择,但有限制:不能設置自定義頭部拔莱,不能發(fā)送和接收cookie,獲取不到getAllResponseHeaders()的返回值
// 帶憑據(jù)的請求
withCredentials屬性設置為true
// 服務器接收到帶憑據(jù)的請求后碗降,會用下面的頭部來請求,如果響應不包含這個頭部塘秦,瀏覽器將不會把響應數(shù)據(jù)交給js
Access-Control-Allow-Credentials: true
// 跨瀏覽器的cros
function createCORSRequest(method,url){
let xhr = new XMLHttpRequest();
if("withCredentials" in xhr){
xhr.open(method,url,true);
}else if(typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method,url);
}else{
xhr = null;
}
return xhr
}
let req = createCORSRequest("get","http://www.baidu.com/page/");
if(req){
req.onload = function(){
// 對響應數(shù)據(jù)進行處理
};
req.send();
}
/* 以上提供的公共方法有
abort() 用于停止正在進行的請求
onerror 用于替代onreadystatechange檢驗錯誤
onload 用于替代onreadystatechange檢驗成功
responseText 用于取得響應內(nèi)容
send() 用于發(fā)送請求
*/
// 其他跨域技術(shù)
1.圖像ping---常用于跟蹤用戶點擊頁面和動態(tài)廣告曝光數(shù)讼渊,只能get請求
var img = new Image();
img.onload = img.onerror = function(){
// 操作
}
img.src = "http://baidu.com?name=xujaing";
2.JSONP---可以直接訪問響應文本,可以在瀏覽器和服務器之間進行雙向通信尊剔,但有安全隱患
function handleResponse(data){
console.log(data);
}
var script = document.createElement("script");
script.src = "http://a.net/json/?callback=handleResponse";
document.body.insertBefore(script, document.body.firstChild);
3.Comet (服務器推送SSE)
常用的技術(shù)有長輪詢和流
4.Web Sockets