一. fetch概述
1. 基本特性
- 更加简单的数据获取方式,功能更强大、更灵活,可以看做是xhr的升级版
- 基于Promise实现
2. 语法结构
fetch(url).then(fn2)
.then(fn3)
...
.catch(fn)
3. fetch的基本用法
通过调用fetch的API——data.text() 来获取数据,但是因为这个API返回的是Promise对象,故而把它return出去,然后在下一个.then 里面获取到真正的数据。
fetch('/abc').then(data=>{
// text()方法属于fetch API的一部分,它返回一个Promise实例对象,用于获取后台返回的数据。
return data.text();
}).then(ret=>{
// 注意这里得到的才是最终的数据
console.log(ret);
});
4. fetch请求参数
- 4.1 常用配置选项
- method(String): HTTP请求方法,默认为GET(GET、POST、PUT、DELETE)
- body(String): HTTP的请求参数
- headers(Object): HTTP的请求头,默认为{}
fetch('/abc', {
method: 'get'
}).then(data=>{
return data.text();
}).then(ret=>{
// 注意这里得到的才是最终的数据
console.log(ret);
});
- 4.2 GET请求方式的参数传递
(1)方式一:传统方式的URL传递参数 (用 ? 方式传递参数)
fetch('/abc?id=123').then(data=>{
return data.text();
}).then(ret=>{
console.log(ret);
});
(2)方式二:Restful形式的URL传递参数 (直接用 / 方式传递参数)
fetch('/abc/123',{
method: 'get'
}).then(data=>{
return data.text();
}).then(ret=>{
console.log(ret);
});
- 4.3 DELETE请求方式的参数传递
fetch('/abc/123',{
method: 'delete'
}).then(data=>{
return data.text();
}).then(ret=>{
console.log(ret);
});
- 4.4 POST请求方式的参数传递
(1)方式一
fetch('/apples',{
method: 'post',
body: 'uname=