一、为什么要封装http接口?
开发过程中有可能经历本地、测试、上线等情况,时常需要更换不同服务器的情况,在ajax请求过多情况下对后期维护是大工程。这里把基地址跟接口分开,如果要修改服务器,直接在文件修改就可以试所有引用代码修改。
二、封装步骤
JS部分:单独js文件
//准备自调用函数,防止污染
(function (w) {
//1.项目基地址: 基地址(http协议域名+端口)
const baseURL = 'http://localhost:8080/api/v1';
//2.接口,设置对象:变量名{属性:基地址+接口}
const urlHttp = {
index_latest: baseURL + '/index/latest',
//可以写入多个接口
}
w.urlHttp = urlHttp
//3.赋值并挂载到window
})(window)
三、引入
html部分
<!-- 业务文件 -->
<script src="./js/index.js"></script>
<!-- 引入接口文件 -->
<script src="./js/http.js"></script>
四、书写业务文件
js业务文件:JQ版本,用这个方法需要在html引用JQ
重点代码:url: urlHttp.index_latest
$(() => {
//入口函数
//ajax发送接收后台数据
$.ajax({
//get请求忽略不写
url: urlHttp.index_latest,
// url调用接口对象
success: function (res) {
//接收响应数据
console.log(res);
}
})
})
原生版本
重点代码: xhr.open('get', urlHttp.index_latest);
//1. 调用构造函数
const xhr = new XMLHttpRequest();
//2.调用open初始化请求: xhr.open(method, url)
xhr.open('get', urlHttp.index_latest);
xhr.onload = function () {
// 4.通过xhr.responseText接受返回数据
console.log(typeof xhr.responseText); //string
const student = xhr.responseText;
console.log(JSON.parse(student)); //转成JSON对象
}
// 3.调用send方法发送请求
xhr.send();
五、效果
JQ效果
原生效果
总结:
1.封装时通常需要注意接口过多,防止命名污染问题,建议用函数封装起来,当然,项目小不用函数也可以直接调用。
2.调用时直接用对象的.
调用方法即可,window可以不写,默认全局寻找.