作者:手机用户2602886335_120 | 来源:互联网 | 2022-12-09 12:15
最近我从JQuery.ajax切换到Fetch API,我不确定fetch API属于新的ES6标准还是H5标准?
1> Rick..:
该提取API是部分HTML生活水平的的WHATWG组织.
该网络超文本应用技术工作组 (WHATWG)是一个组织,维护和发展HTML和API的 Web应用程序.
根据获取生活标准的序言:
在较高的层次上,获取资源是一个相当简单的操作.请求进入,响应出来.然而,该操作的细节非常复杂,并且用于不小心写下并且不同于一个API.
许多API提供了获取资源的能力,例如HTML的img和脚本元素,CSS' 光标和列表样式图像,navigator.sendBeacon()和self.importScripts() Javascript API.Fetch Standard为这些功能提供了统一的体系结构,因此它们在获取的各个方面(例如重定向和CORS协议)都是一致的.
Fetch Standard还定义了fetch() Javascript API,它以相当低的抽象级别公开大多数网络功能.
主要目标fetch()
是使用与XMLHttpRequest相比使用Promises更简单,更简洁的API,使网络请求更容易.
例1:
var myImage = document.querySelector('img');
var myRequest = new Request('flowers.jpg');
fetch(myRequest).then(function(response) {
return response.blob();
}).then(function(response) {
var objectURL = URL.createObjectURL(response);
myImage.src = objectURL;
});
资料来源:MDN
例2:
fetch('./api/some.json').then(respOnse=> {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
return response.json(); // Examine the json in the response
}).then(data =>
console.log(data);
}).catch(err => {
console.log('Fetch Error :-S', err); // deal with error
});
或者用async
/ await
:
async function doWhatever() {
try {
let json = await fetch('./api/some.json').then(x => x.json());
console.log("Got response", json); // do something with it
return json; // can consume doWhatever from other functions
} catch (e) {
// error in request or converting to json or processing
console.log('Fetch error :S', e);
}
}
资料来源:Google Developers