使用原生javascript提供的数据请求
ajax( 四部曲,一般需要我们结合Promise去封装,使用不是很便利,但是效率很高 )fetch( 本身结合了Promise,并且已经做好了封装,可以直接使用 )使用别人封装好的第三方库
目前最流行的,使用率最高的是 axiosaxios得到的结果会进行一层封装,而fetch会直接得到结果
举例:
axios {data: 3, status: 200, statusText: "OK", headers: {…}, config: {…}, …} config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …} data: 3 headers: {content-type: "text/html; charset=UTF-8"} request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} status: 200 statusText: "OK" __proto__: Object fetch 3 //相比上面的 axios , fetch直接输出结果get方法
无参数 get () { // 不带参数的使用 var p = axios.get('http://localhost/get.php') //Promise p .then( res => console.log( res )) .catch ( error => { if ( error ) throw error }) } 有参数 get() { //带参数的使用 axios({ url: 'http://localhost/get.php', params: { //params中跟着的是get请求的参数 a: 1, b: 2 } }) .then(res => console.log(res)) .catch(error => { if (error) throw error }) }post方法
注意: axios中post请求如果直接使用npmjs.com官网文档, 会有坑解决步骤: 先设置请求头实例化 URLSearchParams的构造器函数得到params对象使用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 } })fetch文档 https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch#进行_fetch_请求
fetch请求博客 https://blog.csdn.net/hefeng6500/article/details/81456975