最近测试Jquery插件select2 多数功能都可以实现,但是Ajax始终没办法实现。若是有同学用过,请传授下。
我要实现城市名称的自动完成,类似携程或者去哪儿填写目的地一样。
前端JS代码
$(".js-data-example-ajax").select2({
ajax: {
type: 'POST',
url: "https://ajax.dev", //这是我的测试地址,已经更改Host
dataType: 'json',
delay: 200,
headers: {'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')},
data: function (params) {
return {
location: params.term,
};
},
processResults: function (data, params) {
// 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, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 2,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
服务器Laravel Controller 代码
public function ajax(Request $request){
$keywords=$request->term;
$result=DB::table('locations')->where('name','like',"%$keywords%")->get();
return $result;
}