本文中所有示例均可在https://www.lyz810.com/demo/fetch/中查看演示
实例一、最简单的发送GET请求,返回文本数据
fetch会返回一个promise,可以使用then的第一个函数接收响应对象(Response对象)
function func1(){
fetch('./api.php?action=getPlain')
.then(function (response){
//text方法将响应转为纯文本
return response.text();
})
.then(function (text){
alert(text);
});
}
实例二、发送GET请求,带自定义头,返回json数据
fetch的第二个参数为一个Request对象,headers为请求头的参数,例子中添加了一个自定义的请求头userHeader,值为myHeader
function func2(){
fetch('./api.php?action=getJson',{
headers:{
userHeader:'myHeader'
}
})
.then(function (response){
//json方法将响应转为json对象
return response.json();
})
.then(function (json){
alert(JSON.stringify(json));
});
}
实例三、发送POST请求,通过Request类及Header类,返回json数据
可以直接通过Request类和Header作为fetch的参数
function func3(){
var headers = new Headers();
headers.set('userHeader', 'myHeader');
headers.append('Content-type','application/x-www-form-urlencoded');
var request = new Request('./api.php?action=getJson',{
headers: headers,
method: 'POST'
});
fetch(request)
.then(function (response){
return response.json();
})
.then(function (json){
alert(JSON.stringify(json));
});
}
实例四、发送HEAD请求,只获取响应头的信息
发送HEAD请求,通过response对象的headers属性的get方法可以获取响应头信息
function func4(){
fetch('./api.php?action=getPlain',{
method: 'HEAD'
})
.then(function (response){
alert(response.headers.get('Response-key'))
});
}
实例五、带cookie发送POST请求,包含请求体
默认情况下,fetch不会带着cookie,必须使用credentials: ‘include’参数才可以使请求带上cookie
function func5(){
fetch('./api.php?action=getJson', {
method: 'POST',
credentials: 'include',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'test=test'
})
.then(function (response){
return response.json();
})
.then(function (data){
alert(JSON.stringify(data));
});
}
实例六、POST请求,body内容为formData
body的内容不仅支持字符串还支持formData、Blob等类型
function func6(){
//这种方式可以用来提交表单,上传文件等
var formData = new FormData();
formData.set('key', 'value');
fetch('./api.php?action=getJson', {
method: 'POST',
headers:{
'userHeader': 'This is my header!'
},
credentials: 'include',
body: formData
})
.then(function (response){
return response.json();
})
.then(function (data){
alert(JSON.stringify(data));
});
}