我正在尝试使用单个选择请求根据搜索词“名称”从数据库中检索数据,并使用 select2 填充我的输入字段,这样我就不需要在选择后再次填写表格,但似乎没有得到我在网上搜索但找不到任何解决问题的地方
这是我的选择请求
<script type="text/javascript">
$('.serviceId').select2({
placeholder: 'Select Service',
allowClear: true,
ajax: {
url: '/autocomplete/fetch',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id,
description:item.description,
rate:item.rate
}
})
};
},
cache: true
}
});
这是表格;
<select class="form-select form-select-solid fw-bold serviceId" name="serv_name"></select>
</td>
<td>
{{ Form::text('description[]', null, ['class' => 'form-control form-control-solid']) }}
</td>
<td class="table__qty">
{{ Form::number('quantity[]', null, ['class' => 'form-control qty form-control-solid','required', 'type' => 'number', "min" => 1]) }}
</td>
<td>
{{ Form::text('rate[]', null, ['class' => 'form-control price-input rate form-control-solid','required']) }}
</td>
和控制器文件
/**
*show the application fetch
*
*@return \Illuminate\Htttp\Response
*/
public function fetch(Request $request) {
$data = [];
if ($request->has('q')) {
$search = $request->q;
$data = DB::table('services')
->orderby('name','asc')
->select('id','name', 'description', 'rate')
->where('name', 'like', '%' .$search . '%')
->limit(5)->get();
}
return response()->json($data);
}
我的路线:web.php
Route::get('/autocomplete/fetch', 'InvoiceController@fetch')->name('autocomplete.fetch');
我只需要用户对数量字段进行硬编码。
对不起,我对代码不是很好,任何有价值的帮助将不胜感激。
您正在使用 get 方法向路由发送 ajax 后请求。
尝试更改 web.php:
Route::post('/autocomplete/fetch', 'InvoiceController@fetch')->name('autocomplete.fetch');
如果仍然无法正常工作,请检查 google chrome 中的控制台是否有错误。