Select2 Ajax Laravel - 结果未显示

时间:2016-05-16 07:46:49

标签: php ajax laravel select2

JS

$("#location").select2({
        ajax: {
        url: "/search/locations",
        dataType: 'json',
        delay: 250,
        data: function (params) {
          return {
            q: params.term, // search term
          };
        },
        processResults: function (data) {
            return {
            results: data
            };
        },
        cache: true
      },
        minimumInputLength: 1,
        placeholder: function(){
        $(this).data('placeholder');
        }
      });

控制器

 public function searchLocations()
        {
            $q = Input::get('q');
            $results = Location::where('suburb', 'LIKE', '%'. $q . '%')
               ->orWhere('state', 'LIKE', '%'. $q . '%')
               ->orWhere('postcode', 'LIKE', '%'. $q . '%')
               ->get();
            return Response::json( $results ); 
        }

我可以看到正在发出的ajax请求,然后收回数据,但它没有显示结果。我正在使用最新版本的Select2(v4.0.2)

1 个答案:

答案 0 :(得分:2)

当您从远程源加载自定义数据时,Select2通常不知道如何处理它们。您需要通过为选项设置templateSelection和为所选选项设置templateResult来指定每个结果的格式,如下所示:

function locationResultTemplater(location) {
      return location.suburb + " " + location.state + " " + location.postcode;
} 

function locationSelectionTemplater(location) {
      if (typeof location.suburb !== "undefined") {
          return locationResultTemplater(location);
      }
      return location.text; // I think its either text or label, not sure.
}
$("#location").select2({
        ajax: {
        url: "/search/locations",
        dataType: 'json',
        delay: 250,
        data: function (params) {
          return {
            q: params.term, // search term
          };
        },
        processResults: function (data) {
            return {
            results: data
            };
        },
        cache: true
      },
        minimumInputLength: 1,
        placeholder: function(){
           $(this).data('placeholder');
        },
        templateResult: locationResultTemplater,
        templateSelection: locationSelectionTemplater

  });

请注意,为了返回HTML标记而不是纯文本,您需要让模板函数返回一个jQuery对象选择器,例如: return $("<div class='styleme'>Content</div>);