Ajax新玩法fetch API

时间:2022-12-21 07:08:03

目前 Web 异步应用都是基于 XMLHttpRequest/ActiveXObject (IE)实现的, 这些对象不是专门为资源获取而设计的,因而它们的 API 非常复杂,同时还需要开发者处理兼容性问题。 虽然开发者普遍使用 $.ajax() 这样的上层包装,但 Fetch API 意在提供更加方便和一致的原生 API, 同时统一 Web 平台上的资源获取行为,包括外链脚本、样式、图片、AJAX 等。同时Fetch API使用Promise,因此是一种简洁明了的API,比XMLHttpRequest更加简单易用。

fetch API 语法

  fetch(url)
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(e) {
console.log("Oops, error");
});
//使用 ES6 的 箭头函数
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))
//使用 async/await 来做最终优化
//使用 await 后,写异步代码就像写同步代码一样爽。await 后面可以跟 Promise 对象,表示等待 Promise resolve() 才会继续向下执行,如果 Promise 被 reject() 或抛出异常则会被外面的 try…catch 捕获。
(async function () {
try {
let response = await fetch(url);
let data = response.json();
console.log(data);
} catch(e) {
console.log("Oops, error", e);
}
})();

GET请求

   fetch(url, {
method: "GET", //默认
headers:{
"Accept": "application/json, text/plain, */*"
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))

POST请求

 fetch(url, {
method: "POST",
headers: {
"Accept": "application/json, text/plain, */*",
"Content-type":"application:/x-www-form-urlencoded; charset=UTF-8"
},
body: "name=hzzly&age=22"
})
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))

使用Fetch请求发送凭证

要使用Fetch发送带有诸如cookie之类的凭证的请求。你可以在选项对象中将credentials属性值设置为“include”:

  fetch(url,{
credentials: "include"
})

封装POST请求

  //将对象拼接成 name=hzzly&age=22 的字符串形式
function params(obj) {
let result = ''
for(let item in obj) {
result += `&${item}=${obj[item]}`
}
if(result) {
result = result.slice(1)
}
return result
} function post(url, paramsObj) {
let result = fetch(url, {
methods: 'POST',
credentials: "include"
headers: {
"Accept": "application/json, text/plain, */*",
"Content-type":"application:/x-www-form-urlencoded; charset=UTF-8"
},
body: params(paramsObj)
})
return result
} let obj = {
name: 'hzzly',
age: 22
}
post(url, obj)
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))

原文 请点击这里React 标配的Fetch是什么?