框架级的数据请求
-
axios ( 第三方库 — 别人封装好的库 )
-
fetch ( javascript 原生提供 )
-
vue这边的数据请求的发展
- vue-resource ( Vue 以前自己封装使用的请求类库 ) ,但是 vue-resource作者已经放弃更新了
- vue-resource 作者推荐我们使用 axios
- vue-resource 用法 和 axios 相似度 90% +
- vue2.0我们基本上使用的都是 fetch / axios
- vue-resource 是有jsonp的
- vue-resource 如果在vue中使用,是挂载当前的 实例( 组件 ) 的$http属性身上的
- 举例 this. h t t p ( o p t i o n s ) t h i s . http( options ) this. http(options)this.http.get() this.$http.post
- axios 和 fetch 没有jsonp 数据请求类型的
-
axios 和 fetch 都是promise
-
axios会对我们请求来的结果进行再一次的封装( 让安全性提高 )
-
案例:
new Vue({
el: '#app',
methods: {
getData () {
//进行get请求
// axios.get() -- $.get()
// axios.post() ---$.post()
// axios(options) -- $.ajax(options)
// var p = axios({
// url: './data/data.json'
// })
// console.log( p ) Promise对象
axios({
url: './data/data.json',
method: 'get',//默认就是get请求
})
.then( res => console.log( res ))
.catch( error => conosle.log( error ))
},
postData () {
// 进行post请求
},
get_myself_php_data () {
axios({
url: 'http://localhost/get.php',
params: {
a: 1,
b: 2
}
})
.then( res => console.log( res ))
.catch( error => console.log( error ))
},
get_be_data () {
// 跨域请求线上数据 - 卖座
axios({
url: 'https://m.maizuo.com/gateway',
headers: {
'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.0.4","e":"154549400038873748996477"}',
'X-Host': 'mall.film-ticket.film.list'
},
params: {
cityId: 330100,
pageNum: 1,
pageSize: 10,
type: 1,
k: 7675918
}
})
.then( res => console.log( res ))
.catch( error => console.log( error ))
}
}
})
- axios 中 post请求
var params = new URLSearchParams() //得到params对象,用来接收参数
// params.append( key, value ) key就是参数名,value就是参数值
params.append( 'a', 2 )
params.append( 'b', 2 )
axios({
url: 'http://localhost/post.php',
method: 'post',
headers: {
'Content-Type': "application/x-www-form-urlencoded" //请求头设置为表单提交的请求头
},
data: params
})
.then( res => console.log( res ))
.catch( error => console.log( error ))
- fetch要手动进行一次数据格式化,但是axios是内部进行了数据的格式化
- fetch get 方法请求数据,参数要直接连接在url上
- fetch 格式化数据 有三种 处理方法
- .json() 格式化 json 类型数据, 将 json类型 string 转换成 json 对象
- .text() 格式化文本
- .blob() 格式化二进制数据
- fetch 如果按照官网文档书写post请求,也有坑, 携带数据出现了问题
- fetch post处理
- 设置请求头
- 通过 new URLSearchPrams 来携带参数
案例
- fetch是原生javascript提供的 , 所以它 可以当做全局变量使用 ,它是挂载在window对象身上的
new Vue({ el: '#app', methods: { getData () { fetch('./data/data.json') .then( res => res.json() ) //对数据进行格式化 .then( data => console.log( data ) ) // 这里的data就是格式化后的数据 .catch( error => console.log( error )) // fetch('https://m.maizuo.com/gateway?cityId=330100&pageNum=1&pageSize=10&type=1&k=7675918') }, postData () { fetch( 'http://localhost/post.php',{ method: 'post', headers: new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交 }), body: new URLSearchParams([["a", 1],["b", 2]]).toString() }) .then( res => res.text() ) .then( data => console.log( data )) .catch( error => console.log( error )) } } })