Ajax (Asynchronous JavaScript and XML) 是一种在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术。无限重新加载通常发生在Ajax请求的回调函数中又触发了相同的Ajax请求,形成了一个无限循环。
let isRequesting = false;
function fetchData() {
if (isRequesting) return;
isRequesting = true;
$.ajax({
url: 'your-api-endpoint',
method: 'GET',
success: function(response) {
// 处理响应
isRequesting = false; // 重置标志
},
error: function() {
isRequesting = false; // 错误时也要重置
}
});
}
$('#myButton').off('click').on('click', function() {
// Ajax请求代码
});
function debounce(func, delay) {
let timer;
return function() {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, arguments), delay);
};
}
const debouncedFetch = debounce(fetchData, 500);
let refreshInterval;
function startAutoRefresh() {
refreshInterval = setInterval(fetchData, 5000);
}
function stopAutoRefresh() {
clearInterval(refreshInterval);
}
let controller;
function fetchData() {
if (controller) {
controller.abort(); // 取消之前的请求
}
controller = new AbortController();
fetch('your-api-endpoint', {
signal: controller.signal
})
.then(response => response.json())
.then(data => {
// 处理数据
})
.catch(err => {
if (err.name === 'AbortError') {
console.log('请求被取消');
}
});
}
通过以上方法,可以有效解决Ajax请求导致的无限重新加载问题。
没有搜到相关的沙龙