【问题标题】:Select2 not loading remote dataSelect2 不加载远程数据
【发布时间】:2013-07-14 03:57:25
【问题描述】:

我在使用 select2 时遇到了一些问题。我尝试按照 API 文档加载远程数据,但是我仍然得到一个加载指示器,没有错误,但没有显示数据。

这是一些代码:https://gist.github.com/Fire-Dragon-DoL/5993136

Javascript:

(function() {
  var $;

  $ = jQuery;

  $(function() {
    $('a.submit-link').on('click', function(ev) {
      ev.preventDefault();
      $(this).closest('form').submit();
    });
    $('.spinner-float').spinner({
      step: 0.01,
      numberFormat: 'n',
      min: 0
    });
    $('.spinner').spinner({
      min: 0
    });
    $('.select2-cities').select2({
      width: 200,
      minimumInputLength: 1,
      dropdownCssClass: 'bigdrop',
      loadMorePadding: 300,
      formatResult: function(obj, container, query, escapeMarkup) {
        console.log("formatResult");
        return obj.name;
      },
      formatSelection: function(obj, container) {
        console.log("formatSelection");
        return obj.name;
      },
      initSelection: function(element, callback) {
        var id;

        console.log("initSelection");
        id = $(element).val();
        if ((id != null) && id !== '') {
          $.ajax(gon.cities_path + '/' + id + '.json', {
            dataType: 'jsonp'
          }).done(function(data) {
            console.log("initSelection callback");
            console.log(data);
            callback(data);
          });
        }
      },
      ajax: {
        url: gon.cities_path + '.json',
        dataType: 'jsonp',
        data: function(term, page) {
          return {
            query: term,
            page: page - 1
          };
        },
        results: function(data, page) {
          console.log("results");
          console.log(data);
          return data;
        }
      }
    });
  });

}).call(this);

这是 json 响应:

{
"total": 8084,
"results": [
{
"cap": 35031,
"id": 8085,
"name": "Abano Terme",
"province": "PD",
"state_id": 25
},
{
"cap": 26834,
"id": 8086,
"name": "Abbadia Cerreto",
"province": "LO",
"state_id": 21
}
],
"more": false
}

还有一部分 html(select2 显示正确,我认为不是问题所在):

<!-- ... -->
<script type="text/javascript">
    //<![CDATA[
    window.gon = {};gon.cities_path="http://localhost:3000/cities";
    //]]>
    </script>
<!-- ... -->
<input class="select2-cities" id="travel_diary_city_id" name="travel_diary[city_id]" type="hidden" value="13987" />

在 gist 文件中,您还可以找到代码的咖啡脚本版本。真正不明白的是console.log无论如何都没有被调用,所以基本上格式化函数和类似的东西都不会被调用。

更新 1:解决了一些 javascript 代码问题,其中一些键位于 ajax 对象而不是构造函数中。

【问题讨论】:

    标签: jquery jquery-select2


    【解决方案1】:

    看起来我在使用 JSONP 而没有在服务器端实现它。将数据类型移动到 json 解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2017-12-23
      • 1970-01-01
      • 2018-01-02
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多