我正在使用Laravel中的搜索自动完成框
视图中的表单代码
<form action = "/searchresult" method = "post">
{{ csrf_field() }}
<input type="text" class="form-control" placeholder="Search Stores, Coupons or Deals" name="mysearch" id="mysearch">
<div class="input-group-btn">
<button class="btn btn-search" type="submit">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</form>
路线
Route::get('/search/autocomplete', ['uses' =>'SearchController@autocomplete']);
JS
$( "#mysearch" ).autocomplete({
source: "search/autocomplete",
minLength: 1,
autoFocus: true,
select: function(event, ui) {
window.location.href = "/deals-coupons/" + ui.item.url;
},
focus: function( event, ui ) { event.preventDefault();}
});
控制器方法
public function autocomplete(Request $request)
{
$term = $request->input('mysearch');
// $term = $request->get('mysearch');
Log::info('Search Term: '.$term);
$results = array();
$queries = DB::table('merchants')
->where ('merchant_name','LIKE', $term.'%')
->take(5)
->get();
foreach ($queries as $query)
{
// Log::info('Query: '.$query);
$results[] = ['id' => $query->merchant_id, 'value' => $query->merchant_name, 'url' => $query->merchant_url_text];
}
return $results;
}
我试过以下
$term = $request->get('mysearch');
$term = $request->input('mysearch');
但这些都没有返回我想要输入的搜索词。正如您所看到的,我正在我的laravel.log文件中记录搜索词,并且每次它都是空的。由于该术语为空,因此始终显示商家表中的前5个结果。
有人可以帮我理解我在做什么错。
答案 0 :(得分:3)
您可以尝试以下
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
@Bean
public DataSource dataSource() {
// In classpath from spring-boot-starter-web
final Properties props = new Properties();
props.put("driverClassName", "com.mysql.jdbc.Driver");
props.put("jdbcUrl", "jdbc:mysql://localhost:3306/master?createDatabaseIfNotExist=true");
props.put("username", "root");
props.put("password", "mysql");
HikariConfig hc = new HikariConfig(props);
HikariDataSource ds = new HikariDataSource(hc);
return ds;
}
$('#mysearch').autocomplete ({
minLength : 1,
autoFocus : true,
source : '/search/autocomplete'
});
答案 1 :(得分:0)
我能够让这个工作。
在服务器端,它是关于使用
$ term = $ request-&gt; input('term');而不是$ term = $ request-&gt; input('mysearch');