二、fetch基本用法
fetch('url').then(function(data){
return data.text();
}).then(function(data){
console.log(data)
})
三、fetch请求参数
- method(String):HTTP请求方法,默认GET(GET/POST/PUT/DELETE)
- body(String):HTTP的请求参数
- headers(objects):HTTP的请求头,默认为{}
1.GET请求参数传递
fetch(url+'?id=123&name=lisi', {
method:'get'
}).then(function(data){
return data.text();
}).then(function(data){
console.log(data);
})
2.DELETE请求参数传递
fetch(url+'?id=123&name=lisi', {
method:'delete'
}).then(function(data){
return data.text();
}).then(function(data){
console.log(data);
})
3.POST请求参数传递
fetch(url, {
method:'post',
body:'uname=lisi&pwd=123',
headers:{
'Content-Type':'application/x-www-form=urlencoded'
}
}).then(function(data){
return data.text();
}).then(function(data){
console.log(data);
})
fetch(url, {
method:'post',
body:JSON.stringify({
uname:'lisi',
pwd:'123456'
}),
headers:{
'Content-Type':'application/json'
}
}).then(function(data){
return data.text();
}).then(function(data){
console.log(data);
})
4.PUT请求参数传递
fetch(url, {
method:'put',
body:JSON.stringify({
uname:'lisi',
pwd:'123456'
}),
headers:{
'Content-Type':'application/x-www-form=urlencoded'
}
}).then(function(data){
return data.text();
}).then(function(data){
console.log(data);
})
5.fetch响应结果
- text():将返回体处理成字符串类型
- json():返回结果和JSON.parse(responseText)一样