0

我以前从未编写过 Ajax,目前我正在尝试编写一个无限滚动页面。当用户向下滚动到页面底部时,应该加载更多项目,但现在它们没有加载。这是我的 Javascript,用于检测它们何时触底并进行 Ajax 调用:

window.onload=function(){
//Find out how many items I have loaded and what filter I am using so I can make the Ajax call
var vloaded = <?php echo $i; ?>;
var vfilter = "<?php echo $filter ?>";
$(window).on('scroll', function () { 
  if ($(window).height() + $(window).scrollTop() >= $(document).height() - 10) {
    //I have reached the bottom of the page, now load items
    alert("loaded is " + vloaded + " and filter is " + vfilter);
    $.post("/organizer/getMore", 
        { filter: vfilter, loaded: vloaded }, 
                function(responseText) {
                    $("grid").append(responseText); 
                },"html");
    //I've loaded the next 30 items, increment my counter for next time
    vloaded +=30;   
  }
});
}

当我触底时会显示警报,并且我的变量正在正确递增。我正在使用 Zend Framework,所以 URL 指向我的getMoreAction()函数:

public function getmoreAction()
{
//Used by Ajax to get more items for the infinite scroll
    //Figure out how I'm filtering items and how many I've already loaded
    $filter = $_POST['filter'];
    $loaded = $_POST['loaded'];
    echo "Filter is ".$filter;
    echo "Loaded ".$loaded;
    //Get all the items in the database ordered by filter
    require_once(APPLICATION_PATH . '/models/ItemArray.php');
    $items = ItemArray::getItems($user->getID(), $filter, $loaded );
    //Return items back to Ajax call, converted to html
    echoItems($items);  
}

我已经知道该getItems功能有效,因为我也在页面首次加载时使用它,并且echoItems只是一个循环来回显每个项目的 html,它也适用于其他地方。动作中的回声永远不会执行,所以我假设我的 post call 有问题,以至于我什至从未进行过这个动作。

4

1 回答 1

1

2个建议。

  1. 使用 jQuery 函数$(document).ready()而不是window.onload属性。
  2. 使用 jQuery 函数$.ajax()代替$.post()

我进行了重构,以便我可以更轻松地阅读它。

// put these in the global scope
var vloaded = <?php echo $i; ?>;
var vfilter = "<?php echo $filter ?>";

$(document).ready() 
{

  // I forgot to leave this in
  $(window).on('scroll', function () 
    {
      var height = $(window).height();
      var scrollTop = $(window).scrollTop();
      var dHeight = $(document).height();

      if( height + scrollTop >= dHeight - 10) 
      {
          alert("loaded is " + vloaded + " and filter is " + vfilter);

          // an AJAX request instead of a POST request
          $.ajax
          (
            {
              type: "POST",
              url: "/organizer/getMore",
              data: { filter: vfilter, loaded: vloaded },
              dataType: "html",
              success: function( responseText, textStatus, XHR )
              {
                // select the element with the ID grid and insert the HTML
                $( "#grid" ).html( responseText );
              }
            }
          );

          // global variable
          vloaded +=30;

      } // if
    }

  ); // on

} // ready
于 2012-06-26T18:09:47.400 回答