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;   
  }
});
}

一番下を押すとアラートが表示され、変数が正しくインクリメントされます。私はZendFrameworkを使用しているので、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をエコーするループであり、他の場所でも機能するためです。アクションのエコーは実行されないので、ポストコールに何か問題があり、このアクションに到達することさえできないと思います。

4

1 に答える 1

1

2つの提案。

  1. $(document).ready()プロパティの代わりにjQuery関数を使用しwindow.onloadます。
  2. $.ajax()代わりにjQuery関数を使用してください$.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 に答える