语法使用:
fetch(参数)
.then(完成的回调函数)
.catch(失败的回调函数)
fetch(url,opts)
.then((response) => {
//请求成功后返回的对象response
//例如:json、text等
return response.text();
return response.json();
})
.then((responseData) => {
//处理请求得到的数据
})
.catch((error) => {
//网络请求失败执行该回调函数,得到错误信息
})
语法很简单,感觉类似于Android新建Notification一样。
then第一个是获取整个数据,第二个是根据第一个数据转换而来的你所需要的数据,也就是说你需要一个json数据那么在第一步返回json就好。
1、GET请求
getRequest(url){
/*网络请求的配置*/
var opts = {
method:"GET"
}
fetch(url,opts)
.then((response) => {
return response.text();
})
.then((responseText) => {
alert(responseText);
})
.catch((error) =>{
alert(error);
})
}
2、POST请求
postRequest(url){
let formData = new FormData();
formData.append("username","SuperBigLw");
formData.append("password","123456");
var opts = {
method:"POST",
body:formData
}
fetch(url,opts)
.then((response) => {
return response.text();
})
.then