我希望使用jQuery和Laravel进行自动完成搜索输入。但是当用户在搜索输入中至少写入2个字母时,我收到错误:
GET http://proj.test/autocomplete-search?term=ca 500 (Internal Server Error)
你知道问题出在哪里吗?我想根据用户在搜索表单中插入的字母来显示会议。
搜索输入:
<div class="col col-md-6">
<h4 class="text-white text-center font-weight-bold">Search</h4>
<form class="main-search">
<input type="text" id="search" class="autocomplete dropdown-toggle" placeholder="Conference, Citiy, Category">
</form>
</div>
Laravel路线:
Route::get('/autocomplete-search', 'AutocompleteController@search');
Laravel AutomcompleteController:
class AutocompleteController extends Controller
{
public function search(Request $request){
$search = $request->term;
$conferences = Conference::where('name', 'LIKE', '%'.$search.'%')->get();
$data= [];
foreach ($conferences as $key => $value){
$data[] = ['id'=>$value->id, 'value' => $value->id + " " + $value->name];
}
//dd($data);
return response($data);
}
}
jquery的:
$("#search").autocomplete({
source: "{{ URL::to('autocomplete-search') }}",
minLength: 2,
select:function(key, value)
{
console.log(value);
}
});
编辑:在“网络”选项卡中,错误显示为:
{message:&#34;遇到非数字值&#34;,例外: &#34; ErrorException&#34;,...}
并指向这一行:
{function:&#34; search&#34;,class:&#34; App \ Http \ Controllers \ AutocompleteController&#34;,输入:&#34; - &gt;&#34;}&#34; 。在&#34; $ data [] = [&#39; id&#39; =&gt; $ value-&gt; id,&#39; value&#39; =&GT; $ value-&gt; id +&#34; &#34; + $ value-&gt; name];
答案 0 :(得分:3)
当您需要使用字符串连接运算符(+
)时,您已使用了加法运算符(.
)。
所以
$data[] = ['id'=>$value->id, ' value' => $value->id + " " + $value->name]
需要成为
$data[] = ['id'=> $value->id, 'value' => $value->id . " " . $value->name]
否则PHP认为您正在尝试对这些字段进行添加,而实际上它们是您想要放入单个变量的文本。
有关哪些运算符在PHP中执行哪些操作的信息,请参阅http://php.net/manual/en/language.operators.php。