我一直在尝试为网页制作实时搜索输入,以便在我的数据库中搜索数据。到目前为止,我已经想出了这个:
控制器:
public function launchsitefilter($site_code, Request $request) {
$launchsites = DB::table('launchsites')->where('site_code', $site_code)->get();
if(! $launchsites){
return abort(404);
}
$launchsitesatellite = DB::table('satellites')->where('site', $site_code)->get();
if ($request->ajax())
{
$output="";
$launchsitesatellite = DB::table('satellites')->where('satname','LIKE','%'.$request->search.'%')
->orWhere('norad_cat_id','LIKE','%'.$request->search.'%');
if ($launchsitesatellite)
{
foreach ($launchsitesatellite as $key => $launchsitesatellites) {
$output ='<tr>'.
'<td>'. $launchsitesatellites->satname .'</td>'.
'<td>'.$launchsitesatellites->norad_cat_id.'</td>'.
'<td>'.$launchsitesatellites->object_type.'</td>'.
'</tr>';
}
}
}
return view('pages/launchsite-filter', compact('launchsites', 'launchsitesatellite'));
}
脚本:
$('#search').on('keyup', function() {
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{$launchsitename->site_code}}',
data : {'search':$value},
success:function(data) {
console.log(data);
}
});
});
刀片:
<input type="text" class="form-control" id="search" name="search"></input>
当我在输入中输入内容时,我在控制台中收到此错误:
GET http://space-observe.dev/launch-site/JSC?search=search term 500(内部服务器错误)
我猜我的控制器出错时Javascript正在运行。您需要做些什么才能使实时搜索工作并显示结果。
答案 0 :(得分:1)
如果您按照以下方式重写代码,则应该可以正常运行:
public function launchsitefilter($site_code, Request $request) {
$launchsites = DB::table('launchsites')->where('site_code', $site_code)->get();
if(! $launchsites){
return abort(404);
}
if ($request->ajax())
{
$output="";
// This is the ->get() I'm referring to in the comments.
$launchsitesatellite = DB::table('satellites')->where('satname','LIKE','%'.$request->search.'%')
->orWhere('norad_cat_id','LIKE','%'.$request->search.'%')->get();
if ($launchsitesatellite)
{
foreach ($launchsitesatellite as $key => $launchsitesatellites) {
$output .='<tr>'.
'<td>'. $launchsitesatellites->satname .'</td>'.
'<td>'.$launchsitesatellites->norad_cat_id.'</td>'.
'<td>'.$launchsitesatellites->object_type.'</td>'.
'</tr>';
}
}
return $output;
}
else {
$launchsitesatellite = DB::table('satellites')->where('site', $site_code)->get();
return view('pages/launchsite-filter', compact('launchsites', 'launchsitesatellite'));
}
}
请注意,在检查网站是否包含发布网站后,该功能会分为两部分。
两个部分都返回自己的响应,ajax部分返回HTML响应,正常部分返回视图。
另请注意我添加的->get()
应该可以解决您的代码所遇到的问题。
最后,当您想要将行添加到.
时,您忘记了一个点($output
),这只会显示最后的结果。