当Window滚动事件的值为true时,我正在获取一些ajax。在“网络”选项卡中,我注意到每个事件都连续触发两次GET请求,即使我已设置超时标志来禁用多次运行ajax函数(当前为3秒)。
为什么会这样?
谢谢。
编辑:我刚注意到的一件事是,在准备就绪的文档中,它会触发两次,因此它甚至可能与滚动无关。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Infinite Scroll</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
var offset = 0;
var limit = 10;
// jsonplaceholder is an working example endpoint.
var apiEndpoint = "https://jsonplaceholder.typicode.com/posts?_offset=";
var working = false;
$(document).ready(function() {
getContent();
});
$(window).scroll(function() {
console.log("Fired if ==", $(window).scrollTop() + $(window).height(), getDocHeight());
if ($(window).scrollTop() + $(window).height() == getDocHeight()) {
if (working == false) {
working = true;
getContent();
//console.log("Fired! Offest = ", offset);
}
}
});
function getContent() {
$.ajax({
type: "GET",
url: apiEndpoint+offset+"&_limit="+limit,
processData: false,
contentType: "application/json",
data: '',
success: function(res) {
//console.log(res);
for (var i = 0; i < res.length; i++) {
// replace title and body with properties you need to extract from res
$('body').append("<div><h1>"+res[i].title+"</h1><p>Content: "+res[i].body+"</p></div>");
}
// no need to run timeout on first use (page load)
if(offset !== 0){
// stop ajax call firing too rapidly
setTimeout(function() {
working = false;
}, 3000)
}
offset += 5;
},
error: function(res) {
console.log("Something went wrong! - ", res);
}
});
}
// Get document height (cross-browser compatibility)
function getDocHeight() {
var D = document;
return Math.max(
D.body.scrollHeight, D.documentElement.scrollHeight,
D.body.offsetHeight, D.documentElement.offsetHeight,
D.body.clientHeight, D.documentElement.clientHeight
);
}
</script>
</body>
</html>