输入下拉列表 select2 中的数据不会提取到数据表中



我使用 select2 做了一个多选输入下拉列表。但是,我真的不确定如何从下拉列表中的数据库中获取我调用的数据,以便我可以在数据表中查看它。这是我的代码:

输入下拉列表选择2的脚本:

$('.ethnicity').select2({
placeholder: 'Select..',
ajax: {
url: '/select2-autocomplete-ajax_ethnicity',
dataType: 'json',
delay: 250,
processResults: function ($ethnicity) {
return {
results:  $.map($ethnicity, function (item) {
return {
text: item.Bangsa_updated,
id: item.id,
}
})
};

用于输入下拉列表的控制器,以便它将选择输入类型:

public function ethnicity(Request $request)
{
$ethnicity = [];
if($request->has('q')){
$search = $request->q;
$ethnicity = DB::table("user")
->select("id","ethnic")
->where('ethnic','LIKE',"%$search%")
->get();           
}
return response()->json($ethnicity);
}

上面的代码仅用于从数据库中选择数据,而不将数据提取到数据表。 下面的控制器将数据捕获到数据表中(我将其用于简单的下拉列表,但是不知道如何更改,因此它对于上面的输入下拉列表很有用。

public function fnFilter(Request $request)
{
if(request()->ajax())
{
if(!empty($request->dataGender))
{
$data = DB::table('user')
->select('id', 'Fn', 'Ln')
->where('ethnic', $request->ethnicity)
->get();
}
else
{
$data = DB::table('user')
->select('id', 'Fn', 'Ln', 'Umur', 'Phone', 'Dob','St', 'Country','Zip','Ct','Jantina')
->get();
}
return datatables()->of($data)->make(true);
}
$dataName = DB::table('modified_dpprs')
->select('ethnic','Jantina')
->groupBy('ethnic')
->orderBy('ethnic', 'ASC')
->get();

return response()->json($dataName);

刀片是:

<select id="ethnicity" class=" ethnicity form-control select2-allow-clear"  style="width:200px;" name="namaDUN" multiple >
                          <option value="">Select</option>

我的想法是将控制器函数种族的结果放入函数 fnFilter 中。但我不知道该怎么做。

you can return response in select2 (controller function) required format 
like
$final_array = [];
$ethnicity = DB::table("user")
->select("id","ethnic");
if ($request->search != '') {
$search = $request->search ;
$ethnicity=$ethnicity->where('ethnic','LIKE',"%$search%");
}
// loop the results to make response
foreach($ethnicity->get() as $key => $value):
$final_array[$key]['id'] = $value->id;
$final_array[$key]['text'] = $value->ethnic;
endforeach;
return ['results' => $final_array];
// function ends here
and select 2 tag in blade file like this
$('.ethnicity').select2({
placeholder: 'Select..',
ajax: {
url: '/select2-autocomplete-ajax_ethnicity',
minimumInputLength: 3,
data: function (params) {
var query = {
search: params.term,
page: params.page || 1
}
return query;
}
}
});     

最新更新