AJAX (Asynchronous JavaScript and XML) 是一种在不重新加载整个页面的情况下与服务器交换数据并更新部分网页的技术。HTTP GET/POST则是两种基本的HTTP请求方法。
// 检查未完成的XHR请求
function checkPendingXHR() {
const pendingXHRs = [];
const xhrProto = XMLHttpRequest.prototype;
const originalOpen = xhrProto.open;
xhrProto.open = function() {
this._url = arguments[1];
pendingXHRs.push(this);
originalOpen.apply(this, arguments);
};
const originalSend = xhrProto.send;
xhrProto.send = function() {
this.addEventListener('loadend', () => {
const index = pendingXHRs.indexOf(this);
if (index > -1) {
pendingXHRs.splice(index, 1);
}
});
originalSend.apply(this, arguments);
};
return {
getPending: () => pendingXHRs.map(xhr => xhr._url),
clear: () => { pendingXHRs.length = 0; }
};
}
const xhrTracker = checkPendingXHR();
// 获取所有待处理XHR
console.log('Pending XHRs:', xhrTracker.getPending());
// 拦截Fetch请求
const originalFetch = window.fetch;
window.fetch = function() {
console.log('Fetch request:', arguments);
return originalFetch.apply(this, arguments)
.then(response => {
console.log('Fetch response:', response);
return response;
});
};
// 取消请求示例
const controller = new AbortController();
const signal = controller.signal;
fetch(url, { signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(err => {
if (err.name === 'AbortError') {
console.log('Request aborted');
}
});
// 取消请求
controller.abort();
通过以上方法,您可以全面检查和管理应用中的AJAX/HTTP请求,确保网络通信的可靠性和性能。
没有搜到相关的文章