前言
目标
1 接口调用方式有哪些
2 如何调用接口
一、xhr
xhr是一个小巧的JavaScript库,它对原生的XMLHttpRequest进行了封装,使你在浏览器环境下能够更方便地发送HTTP请求。与流行的request库兼容,xhr为Node.js和浏览器环境提供了一致的API体验。
使用xhr发起Get请求步骤
1 创建xhr对象
2 调用xhr.open()函数
3 调用xhr.send()函数
4 监听xhr.onreadystatechange事件
//创建一个实现ajaxfunction ajax(url) {const xhr = new XMLHttpRequest()xhr.open("GET", url);xhr.onreadystatechange = function () {if (xhr.readyState == 4 && xhr.status == 200) {console.log(xhr.responseText); // 在控制台中打印响应文本}};xhr.send();}ajax('http://localhost:5500/server/config')
js原生ajax发起的请求xhr
二、jquery
jquery中的接口调用基于xhr开发,是DOM操作
1.安装jquery
npm install jquery
2.引入jquery
import $ from ‘jquery’
Vue.prototype.$ = $
3.使用
get请求
this.$.get('http://localhost:5500/server/config',(res)=>{console.log('res',res)
})
Vue中如何使用jQuery
三、axios
axios底层原理也是基于xhr的,减少了DOM操作。Vue框架设计的其中一个目的就是为了减少DOM的操作,axios
是Vue项目比较推荐
使用的接口调用方式
1.安装
npm install axios
2.引入
import axios from ‘axios’
Vue.prototype.axios = axios
3.使用
get请求
this.axios({method: "get",url: "http://localhost:5500/server/config",}).then(function (res) {console.log(res.data);}).catch(function (err) {console.log(err);});
四、fetch
fetch与xhr平级,但是fetch中有两次promise操作且兼容性比较,不推荐使用
fetch('http://localhost:5500/server/config', {method: 'GET',
})
.then(response => response.json())
.then(data => console.log(data))
五、vue-resource
vue-resource在Vue1.x版本的时候经常被使用,从Vue2.x开始以后基本不使用了,vue-resource的更新维护也已经停止,在开发时不建议使用,了解即可。
1.安装
npm install vue-resource
2.引入
import VueResource from “vue-resource”
// vue.use(插件) VM中会添加 $http
Vue.use(VueResource)
3.使用
get请求
this.$http.get("http://localhost:5500/server/config").then(function (res) {//成功的回调函数console.log(res.data);},function (rep) {//失败的回调函数alert(rep);});
总结
1、xhr是js封装的一个库;
2、jquery基于xhr,接口调用$.get $.post是DOM操作;
3、axios基于xhr,减少DOM操作,推荐使用
;
4、fetch是js封装的,与xhr平级。两次promise操作、兼容性比较差;
5、vue-resource,Vue提供的在vue1.x版本中经常被使用,后续不在更新;