选择2“带有远程数据的无限滚动” - 回调未触发

时间:2013-05-15 09:36:49

标签: javascript ruby-on-rails ajax jquery-select2

按照Select2 project page上的示例,当用户滚动到结果集的底部时,我试图提取更多记录。

<script>
  $(document).ready(function() {
    $('#style_full_name').select2({
        placeholder: "Please type in the make and model",
        minimumInputLength: 3,
        ajax: {
          url: "/list_styles",
          dataType: 'json',
          quietMillis: 100,
          data: function (term, page) { // page is the one-based page number tracked by Select2
            return {
                q: term, //search term
                page_limit: 10, // page size
                page: page, // page number
            };
          },
          results: function (data, page) {
            var more = (page * 10) < data.total; // whether or not there are more results available

            // notice we return the value of more so Select2 knows if more results can be loaded
            return {results: data.styles, more: more};
          }
        },
        formatResult: styleFormatResult, // omitted for brevity, see the source of this page
        dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
        escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
    });
    function styleFormatResult(style) {
      var markup = "<table class='style-result'><tr>";
      if (style.dimage_url !== undefined) {
          markup += "<td class='style-image'><img src='" + style.dimage_url + "'/></td>";
      }
      markup += "<td class='style-info'><div class='style-title'>" + style.full_name + "</div>";
      //if (movie.critics_consensus !== undefined) {
      //   markup += "<div class='movie-synopsis'>" + movie.critics_consensus + "</div>";
      //}
      //else if (movie.synopsis !== undefined) {
      //    markup += "<div class='movie-synopsis'>" + movie.synopsis + "</div>";
      //}
      markup += "</td></tr></table>"
      return markup;
    }
  });
</script>

在Select2页面上测试Rotten Tomatoes API示例并跟踪Chrome控制台中的网络面板时,我可以看到在到达滚动列表底部时会触发回调。当我在上面的自己的用例中滚动到滚动列表的底部时,这不会发生。

1 个答案:

答案 0 :(得分:3)

在挖掘了一下后,我发现问题是“总数”不是我的json响应的一部分,所以var more = (page * 10) < data.total评估为false。以下是使我的样式控制器(RoR)进行无限滚动所需的代码:

  def list_styles 
    #sunspot solr query
    @styles = Style.search { fulltext params[:q]; paginate :page => params[:page], :per_page => params[:page_limit] }

    #Build Json String
    @styles = "{\"total\":#{@styles.total}, \"styles\":#{@styles.results.to_json(:only=>[:id, :full_name], :methods => [:dimage_url, :dimage_url_medium])}}"

    #Render Json Response
    respond_to do |format|
      format.json {render :json => @styles }
    end
  end