赞
踩
fetch
是一种原生 js 对 HTTP 数据请求的方式,是 XMLHttpRequest
的一种更理想的替代方案
Fetch API 提供了一个 JavaScript 接口,用于访问和操纵 HTTP 管道的一些具体部分,例如请求和响应,它还提供了一个全局 fetch()
方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源
fetch()
请求返回一个包含响应结果的promise(resolve 时会传 Response 对象),它只是一个 HTTP 响应,而不是真的 JSON,为了获取 JSON 的内容,我们需要使用 json()
方法(在 Body mixin 中定义,被 Request 和 Response 对象实现)
使用例子:
一般请求:
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 return response.json() }.then(data => { //转换后返回的数据 console.log(data) }).catch(err => { //请求的错误处理 console.log(err) })
HTML
fetch('/users.html')
.then(function(response) {
return response.text()
}).then(function(body) {
document.body.innerHTML = body
})
JSON
fetch('/users.json')
.then(function(response) {
return response.json()
}).then(function(json) {
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
})
fetch()方法的两个参数:
url:必须参数,请求的 URL
init:可选参数,请求的配置对象,配置包括
更多内容请参考:
fetch的使用及和ajax的区别
使用 Fetch
安装npm插件 whatwg-fetch
npm install whatwg-fetch --save
使用
import 'whatwg-fetch'
ie8 下需要安装 fetch-ie8
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。