如何用Ajax配合Laravel实现MySQL LIKE匹配的DataTable行展示?
解决方案
第一步:修正后端代码
你当前的后端代码存在逻辑错误——循环里把整个查询结果集合赋值给了first_name,导致返回的JSON数据格式错误。以下是修正并优化后的代码:
public function search(Request $request){ // 只查询需要的字段,提升性能 $customers = New_Customer_M::orderByDesc('id') ->where('first_name', 'like', '%' . $request->input('search', '') . '%') ->get(['id', 'first_name']); return response()->json($customers); }
第二步:配置路由
在routes/api.php中添加对应路由(替换你的控制器类名):
Route::get('/customers/search', [CustomerController::class, 'search']);
第三步:前端实现(Ajax + DataTable)
1. HTML结构
<div style="margin: 20px;"> <input type="text" id="searchInput" placeholder="输入姓名搜索..." style="padding: 8px; margin-bottom: 10px;"> <table id="customersTable" class="display" style="width:100%"> <thead> <tr> <th>客户ID</th> <th>姓名</th> </tr> </thead> <tbody></tbody> </table> </div>
2. JavaScript代码
确保你已本地引入jQuery和DataTables的CSS、JS文件,然后添加以下代码:
$(document).ready(function() { // 初始化DataTable const customerTable = $('#customersTable').DataTable({ processing: true, searching: false, // 关闭DataTable自带搜索框,用自定义的 ajax: { url: '/api/customers/search', // 对应后端路由 method: 'GET', data: function(params) { // 传递搜索关键词 params.search = $('#searchInput').val().trim(); } }, columns: [ { data: 'id' }, { data: 'first_name' } ] }); // 监听搜索框输入,实时刷新表格数据 $('#searchInput').on('keyup', function() { customerTable.ajax.reload(); }); });
补充说明
- 如果客户数据量很大(上万条),需要开启
serverSide: true,同时后端要处理DataTable传递的分页、排序参数。 - 前端资源请使用本地文件,避免依赖外部CDN。
内容的提问来源于stack exchange,提问作者Nikita Parmoji
相关产品推荐
相关产品推荐

