2009-12-23 93 views
0

我正在使用以下JavaScript来动态加载父页面内的外部页面的内容。外部页面与父页面位于同一个域内,并在数据库中查询博客条目。我正在使用变量“eeOffset”将值传递到外部页面中的数据库查询中,以抵消返回的结果,即如果eeOffset为“5”,则查询将返回第6个数据库中的下一个数据库记录。 “eeLimit”变量设置每个请求返回的项目总数。我遇到的问题是显示在父页面中的条目正在被复制 - 就好像在激发对新项目的请求之前模板页面的URL未被更新。有没有人有任何建议如何克服这个问题?消除重复条目

var eeLoading; // Declare variable "eeLoading" 
var eeTemplate = "http://www.mydomain.com/new_items/query"; // URL to template page 
var eeOffset; // Declare variable "eeOffset" 
var eeLimit = "5" 

//Execute the following functions when page loads 
$(function(){ 
    scrollAlert(); 
    $("#footer").append("<div id='status'></div>"); //Add some html to contain the status and loading indicators 
    updateStatus(); // Update the total number of items displayed 
    }); 

//Update Status 
function updateStatus(){ 
    var totalItems = $("ul.column li").length; 
    eeOffset = totalItems; 
    eeURL = eeTemplate+"/"+eeOffset+"/"+eeOrderby+"/"+eeSort+"/"+eeLimit+"/"; // Build the template page url 
    } 

//Scoll Alert 
function scrollAlert(){ 
    var scrollTop = $("#main").attr("scrollTop"); 
    var scrollHeight = $("#main").attr("scrollHeight"); 
    var windowHeight = $("#main").attr("clientHeight"); 
    if (scrollTop >= (scrollHeight-(windowHeight+scrollOffset)) && eeLoading !== "false"){ 
     $("#status").addClass("loading"); 
     $.get(eeURL, function(newitems){ //Fetch new items from the specified url 
      if (newitems != ""){ //If newitems exist... 
       $("ul.column").append(newitems); //...add them to the parent page 
       updateStatus(); //Update the status 
       } 
      else { 
       eeLoading = "false"; //If there are no new items... 
       $("#status").removeClass("loading"); //Remove the loading throbber 
       $("#status").addClass("finished"); //Add some text 
       } 
      }); 
     } 
    if (eeLoading !== "false") { //If there are still new items... 
     setTimeout("scrollAlert();", 1500); //..check the scollheight every 1500ms 
     } 
    } 

回答

0

看起来您的代码中存在争用条件。如果新项目的请求花费超过1.5秒的时间完成,则在调用updateStatus()之前,将触发下一个请求。我认为,解决这个问题最简单的方法是将这段代码:

if (eeLoading !== "false") { //If there are still new items... 
    setTimeout("scrollAlert();", 1500); //..check the scollheight every 1500ms 
    } 

if语句里面,给updateStatus()调用之后更新网址查询:

if (newitems != ""){ //If newitems exist... 
    $("ul.column").append(newitems); //...add them to the parent page 
    updateStatus(); //Update the status 
    // Move setTimeout here 

这样的状态将在您申请新网址时始终会更新。