框架级的数据请求
1 axios (第三方库 )
axios和fetch 没有 jsonp数据请求类型
axios 和 fetch 都是promise
axios 会对我们请求来的结果进行再次封装
2 fetch (javascript 原生提供)
fetch要手动进行一次数据格式化,但是axios是内部进行了数据的格式化
fetch get 方法请求数据,参数要直接连接在url上
fetch 格式化数据 有三种 处理方法:
1 .json() 格式化 json 类型数据, 将 json类型 string 转换成 json 对象
2 .text() 格式化文本
3 .blob() 格式化二进制数据
fetch 如果按照官网文档书写post请求,有错误, 携带数据会出现问题
fetch post处理
设置请求头
通过 new URLSearchPrams 来携带参数
3 vue 的数据请求发展
vue-resource (vue 原先使用的自己封装使用的请求类库),
但 作者放弃更新了
vue-resource 作者推荐我们使用axios
vue-resource 用法与 axios 相似度 90%
vue2.0 基本使用 fetch / axios
vue-resource 有jsonp
vue- resource 如果在vue 中使用,是挂载当前的实例(组件)的$http 属性身上的
example this.$http(options) this.$http.get() this.$http.post()
- axios 案例:
new Vue({
el: '#app',
methods: {
//进行get请求
// axios.get() -- $.get()
// axios.post() ---$.post()
// axios(options) -- $.ajax(options)
// var p = axios({
// url: './data/data.json'
// })
// console.log( p ) Promise对象
getData () {
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 案例:
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 ))
},
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 ))
}
}
})