我正在嘗試實現即時搜尋欄。即時搜尋正在工作,但它卻輸出了兩次輸出內容,這很煩人。能麻煩您看一下問題出在哪裡嗎?謝謝。
這是我的搜尋功能代碼。
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>
搜尋之前:
搜尋後:
該死,我剛剛發現是什麼原因導致了這個問題。這有點傻。原始程式碼在這裡: https://onecompiler.com/posts/3xy39rm78/ php-blade-for-staff,該錯誤仍然存在。問題是,我添加了一個不必要的附加標籤。輸出被放置在有標籤的地方,就像腳本:
在程式碼的最後一點,它告訴 html 在標籤處列印結果(我不確定這是否正確)。透過刪除附加的tbody標籤,問題就解決了。