ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ajax</title>
</head>
<body>
<script type="module">
function ajax(url, onSuccess, onFailed) {
const xhr = window.XMLHttpRequest
? new XMLHttpRequest()
: new ActiveXObject("Microsoft.XMLHTTP");
xhr.open("GET", url, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
onSuccess && onSuccess(xhr.responseText);
} else {
onFailed && onFailed();
}
}
};
}
let cc = null;
const mitt = {
cache: {},
on(name, func) {
this.cache[name] = func;
},
emit(name, data) {
const fn = this.cache[name];
fn && fn(data);
},
};
function adaptor(config) {
return new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.open(config.method.toUpperCase(), config.url, true);
request.send();
request.timeout = config.timeout;
request.onabort = function () {
reject("[abort] request is abort.");
request = null;
};
if (config.cancel) {
mitt.emit("abort", function onCancel() {
request.abort();
request = null;
reject("【abort】current request is abort.");
});
}
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status === 200) {
setTimeout(
() => resolve(request && request.responseText),
10000
);
} else {
reject("request error");
}
}
};
});
}
function dispatchRequest(config) {
return adaptor(config).then(
function (response) {
return response;
},
function (reason) {
return Promise.reject(reason);
}
);
}
function req(config = {}) {
const chain = [dispatchRequest, undefined];
if (config.interceptor) {
chain.unshift(
config.interceptor.fullfilled,
config.interceptor.rejected
);
}
if (config.cancel) {
mitt.on("abort", function (cancel) {
config.cancel(cancel);
});
}
if (config.adaptor) {
chain.push(config.adaptor.fullfilled, config.adaptor.rejected);
}
let promise = Promise.resolve(config);
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
}
req({
url: "https://api.dweb.club/dweb-api/get-index-data",
method: "get",
interceptor: {
fullfilled: (e) => {
console.log("请求拦截成功", e);
return e;
},
},
adaptor: {
fullfilled: (e) => {
console.log("响应拦截成功", e);
return e;
},
},
cancel(onCancel) {
cc = onCancel;
},
});
</script>
</body>
</html>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述