我正在尝试实现实时搜索栏。实时搜索正在工作,但它却输出了两次输出内容,这很烦人。能麻烦您看一下问题出在哪里吗?谢谢。
这是我的搜索功能代码。
public function search(Request $request) { if ($request->ajax()) { $output = ""; $projects = Project::where('title', 'LIKE', '%' . $request->search . '%') ->where('module_code',$request->module_code) ->get(); $count = count($projects); // $projects = array_unique($projects); if ($projects) { foreach ($projects as $project) { $output .= '<tr>' . '<td>' . $project->team_number . '</td>' . // '<td>' . $count . '</td>' . '<td>' . $project->lab . '</td>' . '<td>' . '<a href="/projects/' . $project->id . '" style="display:block;"><b>' . $project->title . '</b></a>' . '</td>' . '<td>' . $project-> latest_state. '</td>' . '<td>' . $project->team_member_1 . '</td>' . '<td>' . $project->latest_team_member_1_state . '</td>' . '<td>' . $project->team_member_1 . '</td>' . '<td>' . $project->latest_team_member_1_state . '</td>' . '<td>' . $project->team_member_1 . '</td>' . '<td>' . $project->latest_team_member_1_state . '</td>' . '<td>' . $project->ta . '</td>' . '<td>' . $project->created_at . '</td>' . '<td>' . '<button class="btn-sm btn-info pull-left" onclick="location.href = \'/projects/' . $project->id . '\'">Project Details</button> ' . '</td>' . '</tr>'; } return Response($output); } } }
这是在 php Blade 中进行实时搜索的脚本:
<script type="text/javascript"> const getQueryParams = (params, url)=>{ let href = url; let regexp = new RegExp('[?&]' + params + '=([^&#]*)', 'i'); let qString = regexp.exec(href); return qString ? qString[1] : null; } $('#search').on('keyup',function(){ $value = $(this).val(); //alert($value); $qString = getQueryParams('module', window.location.href); $queryString = $.ajax({ type : 'get', url : '{{URL::to('search')}}', data : {'search':$value, 'module_code', $qString}, success:function (data) { //console.log(data); //alert(data); $('tbody').html(data); } }); }) </script>
这是 php Blade 中搜索栏的代码
<div class="col-sm-5"> <input type="text" class="form-control" id="search" name="search" placeholder="Search..."/> </div>
搜索之前:
搜索后:
P粉5510842952024-02-27 00:41:54
该死,我刚刚发现是什么原因导致了这个问题。这有点傻。原始代码在这里: https://onecompiler.com/posts/3xy39rm78/ php-blade-for-staff,该错误仍然存在。问题是,我添加了一个不必要的附加标签。输出被放置在有标签的地方,就像脚本一样:
$('#search').on('keyup',function(){ $value = $(this).val(); $qString = getQueryParams('module', window.location.href); $queryString = $.ajax({ type : 'get', url : '{{URL::to('search')}}', data : {'search':$value, 'module_code': $qString}, // data : {'search':$value}, success:function (data) { //console.log(data); // alert(data); $('tbody').html(data); } }); })
在代码的最后一点,它告诉 html 在标签处打印结果(我不确定这是否正确)。通过删除附加的tbody标签,问题就解决了。