当窗口滚动事件评估为 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>
最佳答案
salam,您的 get 请求是第二个,在第一个请求中,方法类型是“OPTIONS”,表示请求有关通信的信息
了解更多详情DOC
关于jquery - GET 请求在窗口滚动时触发两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54405619/