fetch()方法与XMLHttpRequest类似,fetch也可以发起ajax请求,但是与XMLHttpRequest不同的是,fetch方式使用Promise,相比较XMLHttpRequest更加的简洁。fetch是全局量window的一个方法.
fetch方法的then会接收一个Response实例,值得注意的是fetch方法的第二个then接收的才是后台传过来的真正的数据,一般第一个then对数据进行处理等。例如fetch处理JSON响应时 回调函数有一个json()
方法,可以将原始数据转换为json对象
基本使用:
fetch('test.json', { //url (必须), options (可选)
method:'POST'
})
.then(function(res){
return res.json();
})
.then(function(data){
console.log(data)
//{name: "test", sex: "nan"}
})
url参数是必须要填写的,option可选,设置fetch调用时的Request对象,如method、headers等
比较常用的Request对象有:
- method(String): HTTP请求方法,默认为
GET
- body(String): HTTP的请求参数
- headers(Object): HTTP的请求头,默认为{}
- credentials(String): 默认为
omit
,忽略的意思,也就是不带cookie;还有两个参数,same-origin
,意思就是同源请求带cookie;include
,表示无论跨域还是同源请求都会带cookie
GET请求:
fetch('test.js?id=12') //get方式可直接在url后面传参
.then(function(response){
console.log(response)
return response.json();
})
.then(function(data){
console.log(data)
})
POST请求:
fetch('/api/getItems', {
body: JSON.stringify(params), //json字符串和对象都可以,推荐使用json字符串,这样可以在控制台network里看到请求参数
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'include', // include, same-origin, *omit
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
}).then(response => response.json()).then(res => {
console.log(res)
})
具体参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch