概述
基于promise实现,xhr升级版
fetch(url).then(fn1)
.then(fn2)
......
.catch(fn)
基本用法
fetch(url).then(data => {
return data.text();//fetch API,返回promise实例对象
}).then(ret => {
console.log(ret);//最终真实数据在这里!!
})
基本配置
1、method(String),http请求方式,默认GET
2、body(String),http请求参数
3、headers(Object),http请求头,默认0
//GET方式
fetch(url,{method:'get'}).then(data => {
return data.text();
}).then(ret => {
console.log(ret)
})
//DELETE方式
fetch(url,{method:'delete'}).then(data => {
return data.text();
}).then(ret => {
console.log(ret)
})
//POST方式
fetch(url,{
method:'post',
body:'name=abc&pwd=666',
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({
name:'abc',
pwd:'123'
}),
headers:{
'Content-Type':'application/json' //json
}
}).then(data => {
return data.text();
}).then(ret => {
console.log(ret)
})
//PUT
fetch(url,{
method:'put',
body:JSON.stringify({
name:'abc',
pwd:'123'
}),
headers:{
'Content-Type':'application/json'
}
}).then(data => {
return data.text();
}).then(ret => {
console.log(ret)
})
响应结果
响应数据格式
text() 将返回数据处理成字符串
json() 将返回结果处理成json,hjson,和JSON.parse()一样
fetch(url,{method:'get'}).then(data => {
return data.json();
}).then(ret => {
console.log(ret)
})