fetch概述
1.基本特性- 更加简单的数据获取方式,功能更强大、更灵活,可以看做是xhr的升级版
- 基于Promise
2.语法结构
fetch(url).then(fn2)
.then(fn3)
...
.catch(fn)
3.fetch的基本用法
fetch('/url').then(data=>{
return data.text();
}).then(ret=>{
//注意,这里才是得到的最终数据
console.log(ret);
});
4.fetch请求参数
常用配置选项
- method(String):HTTP请求方法,默认为GET(GET、POST、PUT、DELETE)
- body(String):HTTP的请求参数
- headers(Object):HTTP的请求头,默认为{}
fetch('/url',{
method:'get'
}).then(data=>{
return data.text();
}).then(ret=>{
//注意,这里才是得到的最终数据
console.log(ret);
});
GET请求方式的参数传递
fetch('/url?id=123').then(data=>{
return data.text();
}).then(ret=>{
//注意,这里才是得到的最终数据
console.log(ret);
});
或者
fetch('/url/123',{
methpd:'get'
}).then(data=>{
return data.text();
}).then(ret=>{
//注意,这里才是得到的最终数据
console.log(ret);
});
POST请求方式的参数传递
fetch('/url',{
method:'post',
body:'uname=list&pwd=123',
headers:{
'Content-Type':'application/x-www-form-urlencoded',
}
}).then(data=>{
return data.text();
}).then(ret=>{
//注意,这里才是得到的最终数据
console.log(ret);
});
这样发送出的数据是用&符号连接的
也可以用JSON形式发送数据
fetch('/url',{
method:'post',
body:JSON.stringify({
usname:'list',
pwd:123
})
headers:{
'Content-Type':'application/json',
}
}).then(data=>{
return data.text();
}).then(ret=>{
//注意,这里才是得到的最终数据
console.log(ret);
});
fetch相应结果
相应数据格式
- text():将返回体处理成字符串类型
- json():返回结果和JSON.parse(responseText)一样
1287

被折叠的 条评论
为什么被折叠?



