1、建立两个js文件
- 调用接口列表 api.js
- 调用请求方法 http.js
http.js内容
javascript">let origin = 'http://cms.11lou.cn/index.php/api/' // 后端接口域名
/**
* 发起HTTP请求的API封装函数
* @param {string} type 请求类型,如GET、POST等
* @param {string} _url 请求的URL路径
* @param {Object} params 请求的参数,默认为空对象
* @param {Object} headers 请求头的参数,默认为空对象
* @returns 返回httpRequest函数处理后的结果
*/
function httpApi(type, url, params = {},headers = {}) {
// 构造请求配置对象
let object = {
method: type || 'GET', // 默认请求方法为GET
url: origin+url, // 通过address对象获取完整的请求URL
data: params, // 设置请求参数
headers:headers
}
// 发起HTTP请求
return httpRequest(object);
}
/**
* 发起 HTTP 请求的函数
* @param {Object} obj - 配置对象,包含请求的参数,如 method, url, data, dataType, headers
* @returns {Promise} 返回一个 Promise 对象,可以通过 then/catch 来处理请求的成功与失败
*/
function httpRequest(obj) {
return new Promise((resolve, reject) => {
// 创建 XMLHttpRequest 对象
const xmlHttp = createXMLHttpRequest();
if (!xmlHttp) {
alert("浏览器不支持 xmlHttp");
return;
}
const httpMethod = (obj.method || "Get").toUpperCase();
const httpDataType = obj.dataType || 'json';
const httpUrl = encodeURI(obj.url); // 对 URL 进行编码
const async = true;
const headers = obj.headers || {};
let requestData;
if (httpMethod === "POST") {
requestData = buildRequestData(obj.data);
}
// 发起 GET 或 POST 请求
xmlHttp.open(httpMethod, httpUrl, async);
if (httpMethod === "POST") {
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
// 设置自定义请求头
for (const [headerName, headerValue] of Object.entries(headers)) {
xmlHttp.setRequestHeader(headerName, headerValue);
}
xmlHttp.send(requestData);
// 处理请求状态变化
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
handleResponseData(xmlHttp.responseText, resolve, reject, httpDataType);
} else {
reject(new Error(`请求失败,状态码: ${xmlHttp.status}`));
}
}
};
});
}
// ... 其他辅助函数保持不变 ...
// 封装创建 XMLHttpRequest 对象的函数
function createXMLHttpRequest() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
// 构建查询字符串
function buildRequestData(data) {
if (!data) return "";
return new URLSearchParams(data).toString();
}
// 根据不同的数据类型处理响应数据
function handleResponseData(responseText, resolve, reject, dataType) {
try {
if (dataType === 'json') {
let res = JSON.parse(responseText);
if (res && res.code === 1) {
resolve(res);
} else {
reject(res);
}
} else if (dataType === 'text') {
resolve(responseText);
}
} catch (error) {
reject(error);
}
}
api.js内容
javascript">
const address = {
info: 'cms.Index/index', // 后端接口
}
2、调用方式
<!-- 调用接口列表 -->
<script src="./js/http/api.js"></script>
<!-- 调用请求方法 -->
<script src="./js/http/jmhttp.js"></script>
<script>javascript">
httpApi("get", address.info,{},{token:123}).then(result => {
console.log(result);
})
.catch(error => {
console.error(error);
});;
</script>```