Select2 Ajax Laravel - 结果未显示

Select2 Ajax Laravel - results not showing

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)

当您从远程源加载自定义数据时,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

  });

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