Fetch API
Fetch API提供了一个fetch()方法,它被定义在BOM的window对象中,你可以用它来发起对远程资源的请求。 该方法返回的是一个Promise对象,让你能够对请求的返回结果进行检索。
为什么使用Fetch
传统ajax,必须使用它的实例来执行请求和接收返回响应。
通过FetchAPI可以明确配置请求对象。
fetch(url,{
method:"POST",
body:JSON.stringify(data),
headers: {"Content-Type":"application/json"},
credentials:"same-origin"
}).then(function(response){
response.status//=> number 100–599
response.statusText//=> String
response.headers//=> Headers
response.url//=>String
response.text().then(function(responseText){ ... })},function(error){
error.message//=> String
})
url
定义要获取的资源。
一个USVString字符串,包含要获取资源的URL
一个Requeset对象
options(可选)
一个配置项对象,包括所有对请求的设置。可选参数有:
method:请求使用的方法,如GET、POST。
headers:请求的头信息,形式为Headers对象ByteString。
body:请求的body信息:可能是一个Blob、BufferSource、FormData、URLSearchParams
mode:请求的模式,如cors、no-cors或者same-origin。
credentials:请求的credentials,如omit、same-origin或者include。
cache:请求的cache模式:default,no-store,reload,no-cache,force-cache, 或者only-if-cached
response
一个Promise,resolve时回传Response对象:
属性:
status (number) -HTTP请求结果参数,在100–599 范围
statusText (String)- 服务器返回的状态报告
ok (boolean)- 如果返回200表示请求成功则为true
headers (Headers)- 返回头部信息,下面详细介绍
url (String)- 请求的地址
方法:
text()- 以string的形式生成请求text
json()- 生成JSON.parse(responseText)的结果
blob()- 生成一个Blob
arrayBuffer()- 生成一个ArrayBuffer
formData()- 生成格式化的数据,可用于其他的请求
其他方法:
clone()
Response.error()
Response.redirect()
response.headers
has(name) (boolean)- 判断是否存在该信息头
get(name) (String)- 获取信息头的数据
getAll(name) (Array)- 获取所有头部数据
set(name, value)- 设置信息头的参数
append(name, value)- 添加header的内容
delete(name)- 删除header的信息
forEach(function(value, name){ ... }, [thisContext])- 循环读取header的信息
GET请求
fetch('/users.html')
.then(function(response){
returnresponse.text()
}).then(function(body){
document.body.innerHTML = body
})
POST请求
fetch('/users', {
method:'POST',
headers: {
'Accept':'application/json',
'ContentType':'application/json'
},
body: JSON.stringify({
name:'Yancy',
login:'Yancy',
})
})
采用promise形式
var promise =new Promise(function(resolve, reject){
if(/* 异步操作成功 */){
resolve(value);
}else{
reject(error);
}
});