FETCH API提供了一个JavaScript接口,用于访问和操作HTTP管道的某些部分,例如请求和响应。它还提供了一种全局fetch()方法,它提供了一种简单、逻辑的方法来跨网络异步地获取资源。
与jquery.ajax()方法不同的两点:
1、即使响应返回404、500等错误,它也不会出错,只会返回一个网络错误。
2、默认情况下,fetch不会发送和返回cookie。但可以通过初始化参数添加这项功能,var init = {credentials: 'include' // 请求带上cookies}。这点在需要权限验证的操作时一定要注意。
基础用法:
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
Supplying request options
// Example POST method implementation:
postData(`http://example.com/answer`, {answer: 42})
.then(data => console.log(data)) // JSON from `response.json()` call
.catch(error => console.error(error));
const postData = (url = ``, data = {}) => {
// Default options are marked with *
return fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, same-origin, *omit
headers: {
"Content-Type": "application/json; charset=utf-8",
// "Content-Type": "application/x-www-form-urlencoded",
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
body: JSON.stringify(data), // body data type must match "Content-Type" header
})
.then(response => response.json()) // parses response to JSON
.catch(error => console.error(`Fetch Error =\n`, error));
};
如果需要发送包含凭证的需求
fetch('https://example.com', {
credentials: 'include'
})
credentials: 'omit'
返回json类型的数据
var url = 'https://example.com/profile';
var data = {username: 'example'};
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
浏览器支持
桌面:Chrome 42以上,Edge 14以上,IE不支持,Firefox 52以上全支持,Opera 29以上,Safari (WebKit) 10.1以上。
移动:Android Webview 42以上,Chrome for Android 42以上,Firefox Mobile (Gecko) 支持,Safari Mobile 10.1以上,IE Phone不支持,Opera Mobile 暂不知道