数据请求在前端开发中的使用有两种形式
-
使用原生javascript提供的数据请求
-
ajax( 四部曲,一般需要我们结合Promise去封装,使用不是很便利,但是效率很高 )
const ajaxPromise = function(params) { return new Promise((resovle, reject) => { let xhr = new XMLHttpRequest(); xhr.open(params.type || "get", params.url, true); xhr.send(params.data || null); xhr.onreadystatechange = () => { if (xhr.readyState===4 && xhr.status===200) { resovle(JSON.parse(xhr.responseText)); } else { reject(JSON.parse(xhr.responseText)); } } }) } -
fetch( 本身结合了Promise,并且已经做好了封装,可以直接使用 )
fetch(url).then(response => response.json()) .then(data => console.log(data)) .catch(e => console.log("Oops, error", e))
-
vue中我们最常使用的
- vue 1.x 的版本提供了一个封装库 vue-resource , 但是到了vue 2.x版本之后,这个就弃用了 vue-resource使用方法和 axios 相似度在 95% vue-resouce有jsonp方法,但是axios是没有的
- vue2.x版本我们最用使用的数据请求是 axios 和 fetch
数据请求的类型
- get post head put delete option
Axios总结
-
get方法
A: 无参数 axios.get(url).then(res=>console.log(res).catch(error=>conosle.log(error)) B: 有参数 axios({ url: 'http://xxx', method: 'get' //默认就是get,这个可以省略, params: { key: value } }) -
post
注意: axios中post请求如果你直接使用npmjs.com官网文档, 会有坑 解决步骤: 1. 先设置请求头 2. 实例化 URLSearchParams的构造器函数得到params对象 3. 使用params对象身上的append方法进行数据的传参 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; let params = new URLSearchParams() // params.append(key,value) params.append('a',1) params.append('b',2) axios({ url: 'http://localhost/post.php', method: 'post', data: params, headers: { //单个请求设置请求头 'Content-Type': "application/x-www-form-urlencoded" } }) .then(res => { console.log( res ) }) .catch( error => { if( error ){ throw error } })