2015-10-20 92 views
3

首先,这里是我的代码到目前为止。Laravel 5 with Select2,使用ajax加载数据

我的路线:

Route::get('cities/citybylang/{lang_id}', [ 
     'uses' => '[email protected]', 
     'as' => 'dashboard.cityByLanguage' 
]); 

我的控制器:

public function cityByLanguage($lang_id){ 
    $cities = City::select('name','id')->where('lang_id',$lang_id)->get(); 

    return $cities; 
} 

我的观点选择

<select class="js-data-example-ajax"> 
    <option value="3620194" selected="selected">select2/select2</option> 
</select> 

我的选择二代码

$(".js-data-example-ajax").select2({ 
        ajax: { 
        url: "/dashboard/cities/citybylang/1", 
        dataType: 'json', 
        delay: 250, 

        data: function (params) { 
         console.log(params.term); 
         return { 
         q: params.term, // search term 
         page: params.page, 
         name: params.name 
         }; 
        }, 
        beforeSend: function(jqXHR, settings) { 
          console.log(settings.url); 
        }, 
        processResults: function (data, page) { 
         console.log(data); 

         // parse the results into the format expected by Select2. 
         // since we are using custom formatting functions we do not need to 
         // alter the remote JSON data 
         return { 
         results: data 
         }; 
        }, 
        cache: true 
        }, 
        escapeMarkup: function (markup) { return markup; }, // let our custom formatter work 
        minimumInputLength: 1, 
        templateResult: formatRepo, // omitted for brevity, see the source of this page 
        templateSelection: formatRepoSelection // omitted for brevity, see the source of this page 
       }); 
      }); 


      function formatRepo (repo) { 
       if (repo.loading) return repo.text; 
       var markup = '<div class="clearfix">' + 
       '<div clas="col-sm-10">' + 
       '<div class="clearfix">' + 
       '<div class="col-sm-6">' + repo.name + '</div>' + 
       '<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + repo.name + '</div>' + 
       '<div class="col-sm-2"><i class="fa fa-star"></i> ' + repo.name + '</div>' + 
       '</div>'; 

       if (repo.name) { 
        markup += '<div>' + repo.name + '</div>'; 
       } 

       markup += '</div></div>'; 

       return markup; 
      } 


      function formatRepoSelection (repo) { 
       return repo.name || repo.text; 
      } 

Okey,基本问题是,我无法将正确的参数传递给控制器​​。 这是如何工作的,现在我开始输入到选择栏,并给它与具有LANG_ID城市名单= 1
所以Ajax调用发送此控制器:
somthing.com/ ?仪表板/城市/ citybylang/1 q =价值,我键入选择栏]
我有漂亮的网址,所以我想是这样的:
somthing.com/dashboard/cities/citybylang/ [价值,我键入到选择字段]


所以问题是,我怎么能传递参数到控制器中 正确的方式?

回答

1

这个问题很老,但我一直在寻找同样的东西,那就是我如何管理它。

url: function(params) { 
    return '/some/url/' + params.term; 
}, 

下面是引用链接 https://select2.github.io/options.html