现在的 web 开发中已经很少使用 jQuery 库,自然也就用不到它的 ajax() 方法。现在最流行的 web api 请求方式便是 fetch ,它比传统的 ajax 请求方式更加一体化,现在主流浏览器都已经开始支持(什么?IE呢?你说什么?我听…不…到),即使有不支持的情况,也可以使用第三方的 polyfill 库 https://github.com/github/fetch

开始

开发中需求最多的就是请求接口,获取 JSON 数据,以 ip-api 开放 api 作为例子,发出 GET 请求,并获取当前请求 ip

1
2
3
4
5
6
7
8
fetch('http://ip-api.com/json')
.then(function(response){
return response.json();
}).then(function(data){
console.log(data.query); // 223.72.61.32
}).catch(function(e) {
console.log(e);
});

fetch 返回一个 Promise ,这种写法比传统的 ajax 写法更加舒服,如果当前开放环境支持 ES6 ,还可以使用箭头函数,会看起来更加舒服

1
2
3
4
fetch('http://ip-api.com/json')
.then(res ==> res.json())
.then(data ==> console.log(data.query))
.catch(e ==> console.log(e));

如果你想把写法更加的 try/catch 可以使用 async/await 来做优化

1
2
3
4
5
6
7
try {
let response = await fetch(url);
let data = await response.json();
console.log(data);
} catch(e) {
console.log(e);
}

不过这是 ES7 的新特性,现在普及为时过早,感兴趣的话可以看它的完整规范,你也可以看阮一峰的 async 函数的含义和用法

更多用法

获取HTML

1
2
3
4
5
6
fetch('/users.html')
.then(function(response) {
return response.text()
}).then(function(body) {
document.body.innerHTML = body
});

Response 的头信息在 headers 中,使用 get 方法获取,以及状态信息

1
2
3
4
5
6
fetch('/users.json').then(function(response) {
console.log(response.headers.get('Content-Type'))
console.log(response.headers.get('Date'))
console.log(response.status)
console.log(response.statusText)
});

Form 表单提交

1
2
3
4
5
6
var form = document.querySelector('form')

fetch('/users', {
method: 'POST',
body: new FormData(form)
})

JSON 数据提交

1
2
3
4
5
6
7
8
9
10
fetch('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Hubot',
login: 'hubot',
})
});

更多使用见文档
在 Node 中使用 fetch node-fetch

封装

Fetch 用法很简洁,但每次都写几次 then, catch 也会很烦,我们可以对他进行简单封装,让每次使用不那么麻烦。这里只是提供一种思路,因为每个项目设计到的情况都有少许不同

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
function fetchGet(url) {
return fetchRequest(url, 'GET')
}
function fetchPost(url, params) {
return fetchRequest(url, 'POST', params)
}
function fetchRequest(url, method, params) {
var headers = {
"authorization": "XXXXXXXXX"
}
if( method.toLowerCase() == 'post' ){
headers['Content-Type']= 'application/json'
}
return new Promise(function(resolve, reject) {
fetch(url, {
method: method,
headers: headers,
body: JSON.stringify(params)
}).then(res => {
return res.json()
}).then(data => {
resolve(data)
}).catch(e => {
console.log(e);
// 需要统一的处理错误方式,避免每次都catch
})
})
}

// 使用
fetchGet('http://ip-api.com/json')
.then(data => {
console.log(data);
})

fetch 方法返回的是 Promise ,我们的封装方法也要返回 Promise,我只返回 JSON 数据,catch 的数据集中处理。

timeout

fetch 本身不带 timeout ,需要自己封装,详情见 Javascript 给 Fetch 加上 Timeout

参考文献

03-16 18:47