[英]JQuery AJAX call function running twice
編輯:不幸的是,答案和建議還沒有完全解決問題。 我可能不得不切換到“查看更多帖子”按鈕而不是使用滾動,因為我認為這是問題所在。 很高興最終得到一個解決方案,雖然我找不到任何地方。
我的解決方案是添加超時事件。 可怕又臟。 這個:
complete: function (data) {
setTimeout(function() {
$("#loading-posts").fadeOut("fast");
$isFetchingNotes = false;
}, 1000);
}
我為我的網站寫了一個自定義博客。 當用戶滾動時,較舊的帖子會出現並通過JQuery AJAX自動加載。 這是有效的 - 然而,它似乎比我想要的更多次地獲取數據2,3或4。 實際上我只希望它一次獲取數據。 所以我放了一個“正在運行”的類型變量,但是它也沒有工作,它仍然不止一次地獲取數據並復制帖子。 這是我的代碼:
$(window).scroll(function(){
var $scroll = $(window).scrollTop();
var $docHeight = $(document).height();
var $winHeight = $(window).height();
var $lastPost = ($(".note-area:last").attr("id") - 1);
if($scroll === $docHeight - $winHeight) {
if(!$isFetchingNotes) {
var $isFetchingNotes = true;
$("div.more-posts").show();
$("#loading-posts-gif").fadeIn("slow");
$.ajax({
type: "GET",
url: 'loadnotes.php" ?>',
data: {
'lastPost': $lastPost
},
cache:true,
success: function(data) {
if(data) {
$('div#post-area').append(data);
$('div.more-posts').hide();
} else {
$('div.more-posts').replaceWith("<h4>-- End of notes --</h4>");
}
},
complete: function () {
$("#loading-posts").fadeOut("fast");
}
}).error(function (event, jqXHR, ajaxSettings, thrownError) {
$('div.more-posts').html("<h2>Could not retrieve data</h2>");
});
$isFetchingNotes = false;
} // End if $isfetchingnotes
} // End if scroll load point
}); // End onscroll event
任何人都可以說明盡管$ isFetchingNotes變量設置為true,為什么它可能試圖繼續獲取數據? 謝謝!
你需要在scroll
函數之外聲明$isFetchingNotes
變量:
var $isFetchingNotes = false;
$(window).scroll(function(){
...
}
在ajax完成后再次將其更改為false:
complete: function(){
$isFetchingNotes = false;
...
}
Razzak得到了一半。 你需要函數外部的$isFetchingNotes
變量,並且在加載完成之后(在complete
回調中)你不需要將它返回到false。 這里是:
var $isFetchingNotes = false;
$(window).scroll(function(){
var $scroll = $(window).scrollTop();
var $docHeight = $(document).height();
var $winHeight = $(window).height();
var $lastPost = ($(".note-area:last").attr("id") - 1);
if($scroll > $docHeight - $winHeight) {
if(!$isFetchingNotes) {
$isFetchingNotes = true;
$("div.more-posts").show();
$("#loading-posts-gif").fadeIn("slow");
$.ajax({
type: "GET",
url: 'loadnotes.php" ?>',
data: {
'lastPost': $lastPost
},
cache:true,
success: function(data) {
if(data) {
$('div#post-area').append(data);
$('div.more-posts').hide();
} else {
$('div.more-posts').replaceWith("<h4>-- End of notes --</h4>");
}
},
complete: function () {
$("#loading-posts").fadeOut("fast");
$isFetchingNotes = false;
}
}).error(function (event, jqXHR, ajaxSettings, thrownError) {
$('div.more-posts').html("<h2>Could not retrieve data</h2>");
});
} // End if $isfetchingnotes
} // End if scroll load point
}); // End onscroll event
此外,我建議不要將條件設置為$scroll
正好位於該位置,因為它不會為每個滾動像素觸發。 你最好放:
if($scroll > $docHeight - $winHeight) { ...
代替:
if($scroll === $docHeight - $winHeight) { ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.