3.1 fetch 概述
1.基本特性
·更加简单的数据获取方式,功能更强大、更灵活,可以看做是xhr的升级版
·基于Promise实现
官方网址(点击)
基本用法
// text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,用于获取后台返回的数据
<script type="text/javascript">
/*
Fetch API 基本用法
*/
fetch('http://localhost:3000/fdata').then(function(data){
// text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,用于获取后台返回的数据
return data.text();
}).then(function(data){
console.log(data);
})
</script>
POST请求方式
//POST请求传参,传统表单形式的数据
fetch('http://localhost:3000/books', {
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)
});
//POST请求传参,使用json格式,要求在 node服务器中加载app.use(bodyParser.json()),用来处理参数
fetch('http://localhost:3000/books', {
method: 'post',
body: JSON.stringify({
uname: '张三',
pwd: '456'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data){
return data.text();
}).then(function(data){
console.log(data)
});
PUT请求方式的参数传递,put一般用在修改方面,跟post比较相似。
//PUT请求传参
fetch('http://localhost:3000/books/123', {
method: 'put',
body: JSON.stringify({
uname: '张三',
pwd: '789'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data){
return data.text();
}).then(function(data){
console.log(data)
});
<script type="text/javascript">
/*
Fetch响应结果的数据格式,如果是text(),结果是字符串,需要转化成json.
*/
fetch('http://localhost:3000/json').then(function(data){
// return data.json();
return data.text();
}).then(function(data){
// console.log(data.uname)
// console.log(typeof data)
var obj = JSON.parse(data);
console.log(obj.uname,obj.age,obj.gender)
})
</script>