- 使用fetch的優(yōu)點
- 語法簡潔秀鞭,更加語義化
- 基于標(biāo)準(zhǔn) Promise 實現(xiàn),支持 async/await
- 同構(gòu)方便稻艰,使用 isomorphic-fetch
為什么要用fetch
XMLHttpRequest 是一個設(shè)計粗糙的 API懂牧,不符合關(guān)注分離(Separation of Concerns)的原則,配置和調(diào)用方式非匙鹞穑混亂归苍,而且基于事件的異步模型寫起來也沒有現(xiàn)代的 Promise,generator/yield运怖,async/await 友好拼弃。
fetch就是為了解決xhr的問題的
使用xhr傳遞一個json請求 ,
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = function() {
console.log(xhr.response);
};
xhr.onerror = function() {
console.log("Oops, error");
};
xhr.send();
使用fetch來傳遞請求
fetch(url).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function(e) {
console.log("Oops, error");
});
與ajax相比
- ajax只能實現(xiàn)同源請求摇展,fetch可實現(xiàn)跨域請求吻氧;
- Fetch代碼很像jQuery中的ajax,但是兩者是不同的,fetch是原生的js盯孙,而jQuery中的ajax是庫封裝的鲁森;
- ajax幾乎所有的主流瀏覽器都支持,但fetch由于目前并沒有被列入標(biāo)準(zhǔn)振惰,只有像firefox最新版歌溉,chrome最新版,以及IE10+等以上才支持骑晶;
一個完整的post請求和響應(yīng)過程
var url = "/fetch";
fetch(url,{
method:"post",
headers:{
"Content-type":"application/x-www-form-urlencoded"
},
body:"name=luwenjing&age=22"
})
.then(function (response){
if (response.status == 200){
return response;
}
})
.then(function (data) {
return data.text();
})
.then(function(text){
console.log("請求成功痛垛,響應(yīng)數(shù)據(jù)為:",text);
})
.catch(function(err){
console.log("Fetch錯誤:"+err);
});
與異步編程相關(guān)的ES7的Async/Await