傳統(tǒng)的Request
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
// Success!
var resp = this.responseText;
} else {
// Error :(
}
}
};
request.send();
request = null;
jQuery ajax
$.ajax({
type: 'GET',
url: '/my/url',
success: function(resp) {
},
error: function() {
}
});
傳統(tǒng)的XMLHttpRequest請求閑的非常的雜亂,而優(yōu)雅的ajax又不得不額外加載jQuery這個80K左右的框架
但是現(xiàn)在饿凛,我們可以使用Fetch祭芦,提供了對 Request 和 Response (以及其他與網(wǎng)絡(luò)請求有關(guān)的)對象的通用定義璧函,它還提供了一種定義,將 CORS 和 HTTP 原生的頭信息結(jié)合起來狼荞,取代了原來那種分離的定義啊楚。
But参袱,Fetch 兼容性电谣,可以看到秽梅,兼容性很差,移動端全軍覆沒剿牺,不過可以使用Fetch polyfill
使用方法
fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function() {
// Your code for handling the data you get from the API
})
.catch(function() {
// This is where you run code if the server returns any errors
});
so easy
現(xiàn)在使用Fetch創(chuàng)建一個簡單的Get請求企垦,將從Random User API獲取的數(shù)據(jù)展示在網(wǎng)頁上
<h1>Authors</h1>
<ul id="authors"></ul>
const ul=document.getElementById('authors');
const url="https://randomuser.me/api/?results=10";
fetch(url)
.then(function(data){
})
.catch(function(err){
});
首先獲取authors,定義常量URL晒来,然后調(diào)用Fetch API并且使用上面定義的常量URL
钞诡,但是此處獲取的并不是JSON,而是需要進行轉(zhuǎn)換湃崩,這些方法包括:
- clone()
- redirect()
- arrayBuffer()
- formData()
- blob()
- text()
- json()
此處我們需要返回的是json對象荧降,所以上面的js應(yīng)該:
fetch(url)
.then((resp) => resp.json()) //轉(zhuǎn)換成json對象
.then(function(data) {
dom操作
})
})
接下來定義兩個函數(shù):
function createNode(el){
return document.createElement(el);
}
function append(parent,el){
retrun parent.appendChild(el);
}
編寫請求成功后操作
fetch(url)
.then((resp)=>resp.json())
.then(function(data){
let authors=data.results;
return authors.map(function(author){
let li=createNode('li'),
img=createNode('img'),
span=createNode('span');
img.src=author.picture.medium;
span.innerHTML=`${author.name.first} ${author.name.last}`;
append(li,img);
append(li,span);
append(ul,li);
})
})
.catch(function(err){
console.log(err)
})
處理更多請求(POST)
Fetch默認是GET方式,此外還可以使用自定義頭部與請求方式攒读,如:
const url = 'https://randomuser.me/api';
// The data we are going to send in our request
let data = {
name: 'Sara'
}
// The parameters we are gonna pass to the fetch function
let fetchData = {
method: 'POST',
body: data,
headers: new Headers()
}
fetch(url, fetchData)
.then(function() {
// Handle response you get from the server
});
還可以使用request構(gòu)建請求對象朵诫,如:
const url = 'https://randomuser.me/api';
// The data we are going to send in our request
let data = {
name: 'Sara'
}
// Create our request constructor with all the parameters we need
var request = new Request(url, {
method: 'POST',
body: data,
headers: new Headers()
});
fetch(request)
.then(function() {
// Handle response we get from the API
})