心里最崇拜的那個人,不必變成那個人,而是用那個人的精神和方法,去變成你自己
----本文來自拉勾大前端
Ajax
- AJAX就是瀏覽器提供的一套API,可以通過javascript調用,從而實現(xiàn)代碼控制請求與響應,通過javascript進行網(wǎng)絡編程
// jQuery 中的 Ajax 方法 $.ajax({ url: "https://jsonplaceholder.typicode.com/users", type: "GET", dataType: "json", data: {"id": 1}, success: function (data) { // 使用請求成功的數(shù)據(jù) console.log(data); } })
ajax請求
- 創(chuàng)建XMLHttpRequest類型的對象
- 準備發(fā)送,打開與網(wǎng)址之間的連接
- 執(zhí)行發(fā)送動作
- 指定xhr狀態(tài)變化事件處理函數(shù)
// 1.創(chuàng)建一個 XMLHttpRequest 類型的對象 --- 相當于打開了一個瀏覽器 var xhr = new XMLHttpRequest(); // 2.打開一個與網(wǎng)址之間的連接 --- 相當于在地址欄輸入網(wǎng)址 xhr.open("GET","https://jsonplaceholder.typicode.com/users"); // 3.通過連接發(fā)送一次請求 --- 相當于點擊回車或者超鏈接 xhr.send(null); // 4.指定 xhr 狀態(tài)變化事件處理函數(shù) --- 相當于處理網(wǎng)頁呈現(xiàn)后的操作 xhr.onreadystatechange = function () { // 通過判斷 xhr 的 readyState ,確定此次請求是否完成 if (this.readyState === 4) { console.log(this.responseText) } }
原生Ajax詳解
- readyState屬性:readyState屬性返回一個XMLHttpRequest代理當前所處的狀態(tài),由于readystatechange事件是在xhr對象狀態(tài)變化時觸發(fā)
- 0:代理XHR被創(chuàng)建,但尚未調用open()方法
- 1:open()方法已經(jīng)被調用,建立了連接
- 2:send()方法已經(jīng)被調用,并且已經(jīng)可以獲取狀態(tài)行和響應頭
- 3:響應體下載中,responseText屬性可能已經(jīng)包含部分數(shù)據(jù)
- 4: 響應體下載完成,可以直接使用responseText
// 1.創(chuàng)建一個 XMLHttpRequest 類型的對象
var xhr = null;
// 兼容寫法
if (window.XMLHttpRequest) {
// 標準瀏覽器
xhr = new XMLHttpRequest();
} else {
// IE 6 瀏覽器
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2.open() 方法開啟請求
// xhr.open("GET","https://jsonplaceholder.typicode.com/users?id=1");
xhr.open("POST","https://jsonplaceholder.typicode.com/users");
// 設置請求頭
// 一般 get 方法不需要設置,而 post 方法必須設置
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
// 3.send() 方法發(fā)送一次請求
// 如果是 get 方法請求,不需要再 send 中傳參數(shù),它如果想傳參數(shù),直接寫在網(wǎng)址上
// xhr.send(null);
xhr.send("name=harry&age=19");
xhr.onreadystatechange = function () {
// 通過判斷 xhr 的 readyState ,確定此次請求是否完成
if (this.readyState === 4) {
console.log(this.responseText)
}
}
同步和異步
- xhr.open()方法第三個參數(shù)要求傳入一個boolean值,作用就是設置此次請求時否采用異步方式執(zhí)行
- 默認為true異步,如果需要同步執(zhí)行可以通過傳遞false實現(xiàn)
- 如果采用同步方式執(zhí)行,則代碼會卡死在xhr.send()
- 建議:為了讓這個事件可靠,在發(fā)送請求send()之前,一定是先注冊readystatechange
數(shù)據(jù)格式
- XML數(shù)據(jù)類型(淘汰)
- JSON數(shù)據(jù)類型
- JSON數(shù)據(jù)不需要存到變量中
- 結束不需要寫分號
- JSON數(shù)據(jù)中屬性名必須加引號
- 使用json對象的parse方法可以將字符串轉換成對象格式
//可以通過這種方法將獲得的json數(shù)據(jù)轉換成字符串 var strObj = JSON.parse(str); console.log(strObj.name)
json-server
- 方便我們自己上傳json數(shù)據(jù),需要在本地搭建一個臨時服務器
- json-server是一個Node模塊,運行Express服務器,你可以指定一個json文件作為api的數(shù)據(jù)源
- 網(wǎng)址:https://github.com/typicode/json-server
- 命令行輸入:json-server --watch 文件名.json
原生Ajax--GET請求
var xhr =new XMLHttpRequest();
//發(fā)送get請求
//在open中傳參
xhr.open("GET","http://localhost:3000/posts?id=1");
xhr.send(null);
xhr.onreadystatechange = function(){
if(this.readyState === 4){
console.log(this.responseText);
}
}
原生Ajax--POST請求
- post請求過程中,都是采用請求體承載需要提交的數(shù)據(jù)
- 需要設置請求頭中的content-type,以便于服務端接收數(shù)據(jù)
- 需要提交到服務端的數(shù)據(jù)可以通過send方法的參數(shù)傳遞
var xhr = new XMLHttpRequest(); //POST請求 xhr.open("POST","http://localhost:3000/posts"); //post要設置請求頭 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //向服務器添加數(shù)據(jù) // xhr.send("age=19") xhr.send(JSON.stringify({ "name": "dxa", "age": 18, "class": "lagou" })) // xhr.send({"age":19}) xhr.onreadystatechange = function(){ if(this.readyState === 4){ console.log(this.responseText) } }
封裝AJAX函數(shù)
// 封裝自己的 Ajax 函數(shù)
/**
* 參數(shù)1:{string} method 請求方法
* 參數(shù)2:{string} url 請求地址
* 參數(shù)3:{Object} params 請求參數(shù)
* 參數(shù)4:{function} done 請求完成后執(zhí)行的回調函數(shù)
*/
function ajax(method, url, params, done) {
// 統(tǒng)一將方法中的字母轉大寫,便于后面判斷
method = method.toUpperCase();
// 書寫 IE 6 的兼容
var xhr = window.XMLHttpRequest
? new XMLHttpRequest()
: new ActiveXObject("Microsoft.XMLHTTP");
// 將對象格式的參數(shù)轉為 urlencoded的格式
var pairs = [];
for (var k in params) {
pairs.push(k + "=" + params[k]);
}
var str = pairs.join("&");
// 判斷是否是 get 方法,需要更改 url 的值
if (method === "GET") {
url += "?" + str;
}
// 創(chuàng)建打開一個連接
xhr.open(method, url);
var data = null;
// 如果是 post 方法,需要設置請求頭,還有請求體
if (method === "POST") {
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
data = str;
}
xhr.send(data);
// 執(zhí)行回調函數(shù)
xhr.onreadystatechange = function () {
if (this.readyState !== 4) return;
// 執(zhí)行外部傳進來的回調函數(shù)即可
// 需要用到響應體
done(JSON.parse(this.responseText));
}
}
// 調用函數(shù)
ajax("GET", "http://localhost:3000/users",{"id": 1},function (data) {
console.log(data);
});
ajax("POST", "http://localhost:3000/users",{"name": "john","age": 19,"class": 2},function (data) {
console.log(data);
});
jQuery中ajax
$.ajax()
- url: 請求地址
- type: 請求方法,默認為get
- dataType: 服務端響應數(shù)據(jù)類型
- contentType: 請求體內容類型,默認application/x-www-form-urlencoded
- data: 需要傳遞到服務端的數(shù)據(jù)
- timeout: 請求超時時間
- beforeSend: 請求發(fā)起之前觸發(fā)
- success: 請求成功之后觸發(fā)
- error: 請求失敗觸發(fā),比如請求地址錯誤
- complete: 請求完成觸發(fā)
$.ajax({ url: "http://localhost:3000/posts", type: "get", dataType: "json", // data: {"id": 1}, beforeSend: function(xhr){ console.log("before send"); }, success: function(data){ console.log(data); }, complete: function(xhr){ console.log(xhr.status) } })
$.get()
- get請求的快捷方式
- $.get(url,data,callback)
$.get("http://localhost:3000/posts",{},function(data){ console.log(data) })
$.post()
- post請求的快捷方式,添加數(shù)據(jù)的方式
$.post("http://localhost:3000/posts",{"name": "dxa"},function(data){
console.log(data)
})
其他數(shù)據(jù)類型
// put 請求,更改數(shù)據(jù)
$.ajax({
url: "http://localhost:3000/comments/4",
type: "put",
dataType: "json",
data: {"content": "good", "postId": 2},
success: function (data) {
console.log(data)
}
})
// delete 請求,刪除數(shù)據(jù)
$.ajax({
url: "http://localhost:3000/comments/5",
type: "delete",
success: function (data) {
console.log(data)
}
})
Axios
- Axios是目前應用最為廣泛的AJAX封裝庫
- 線上文件:https://unpkg.com/axios/dist/axios.min.js
- 參考文檔:http://axios-js.com/zh-cn/docs/
Axios API
- 可以通過向axios()傳遞相關配置來創(chuàng)建請求
- axios(config) config為對象格式的配置選項
- axios(url,config) config可選
常用配置選項
- url 用于請求服務器的URL
- method 創(chuàng)建請求時使用的方法
- baseURL 傳遞相對URL前綴,將自動加在url前面
- headers 即將被發(fā)送的自定義請求頭
- params 即將與請求一起發(fā)送的URL參數(shù)
- data 作為請求主體被發(fā)送的數(shù)據(jù)
- timeout 請求超時的毫秒數(shù)
- responseType 表示服務器響應的數(shù)據(jù)類型,默認json
axios({ url: "/posts", method: "get", baseURL: "http://localhost:3000", params: { id: 1 } }).then(function(res){ console.log(res.data) })
全局默認配置
- 可以指定將被用在各個請求的配置默認項
- 利用axios.defaults修改全局變量
// 全局配置默認值 axios.defaults.baseURL = "http://localhost:3000";
onload/onprogress
- xhr.onload事件:只在請求完成時觸發(fā)
- xhr.onprogress事件: 只在請求進行中觸發(fā)
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:3000/posts");
xhr.onload = function () {
console.log("load",this.readyState)
}
xhr.onprogress = function (e) {
console.log("progress",this.readyState)
// 在周期性請求過程中,接收到的數(shù)據(jù)的個數(shù)
console.log(e.loaded);
// 接收數(shù)據(jù)的總個數(shù)
console.log(e.total);
}
xhr.send(null);
response屬性
- 以對象的形式表述響應體,其類型取決于responseType的值
- responseType要在調用open()初始化請求之后