Fetch:下一代 Ajax 技术
http://www.cnblogs.com/snandy/p/5076512.html
|
1
2
3
4
5
6
7
8
9
10
11
12
|
var
xhr =
new
XMLHttpRequest();
xhr.open(
'GET'
,url);
xhr.onload =
function
() {
// To do with xhr.response
};
xhr.onerror =
() {
// Handling errors
};
xhr.send();
|
以上可以看出,XHR 使用 onXXX 处理,典型的 "事件模式"。
Fetch 目前还不是 W3C 规范,由whatag负责出品。与 Ajax 不同的是,它的 API 不是事件机制,而采用了目前流行的 Promise 方式处理。我们知道 Promise 是已经正式发布的 ES6 的内容之一。
fetch(
'doAct.action'
).then(
(res) {
if
(res.ok) {
res.text().then(
(obj) {
// Get the plain text
})
}
},
(ex) {
console.log(ex)
})
|
以上 fetch 函数是全局的,目前最新的Firefox,Chrome,Opera 都已支持,详见
以上是一个最简单的请求,只要传一个参数 url 过去,默认为 get 请求,获取纯文本,fetch 第二个参数可以进行很多配置,比如 POST 请求
"doAct.action"
|
如果返回的是 JSON, 如下
res 实际上该规范定义的 Response 对象,它有如下方法
- arrayBuffer()
- blob()
- json()
- text()
- formData()
此外,Fetch 跨域请求时默认不会带 cookie,需要时得手动指定 credentials: 'include'
'include'
// ...
})
|
这和 XHR 的withCredentials 一样,只是withCredentials 只要设为 true。
相关:
https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch
https://fetch.spec.whatwg.org
https://hacks.mozilla.org/2015/03/this-api-is-so-fetching
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!