Laravel中Ajax生成的HTML路由链接失效问题求助
解决Laravel控制器中Ajax返回的链接失效问题
问题原因
- 你在控制器的HTML字符串拼接中使用了Blade模板语法
{{route()}},但控制器直接返回纯HTML字符串时,Blade引擎不会解析这些模板语法,导致未处理的代码直接输出。 - 字符串拼接存在语法错误:
'.$user->name.'}}多了一个冗余的}},同时href={{route(...)}}未用引号包裹,不符合HTML属性规范。
修正方案
将链接生成代码改为直接在PHP中调用route()函数生成URL,同时修正字符串拼接错误:
<h3><a href="'.route("profile", ["id" => $user->id]).'">'.$user->name.'</a></h3>
完整修正后的代码
public function search(Request $request) { if ($request->ajax()) { $data = User::where('name','LIKE',$request->name.'%')->where('role','freelancer')->get(); $output = ''; if (count($data)>0) { foreach ($data as $user) { $output .= ' <div class="row freelancer p-1 m-1"> <div class="col-sm-3"> <img src="'.$user->avatar.'" height="100px" width="100px"> </div> <div class="col-sm-9"> <h3><a href="'.route("profile", ["id" => $user->id]).'">'.$user->name.'</a></h3> <p>'.$user->profile->title.'</p> <p>'.$user->profile->about.'</p> </div> </div>'; } }else { $output .= 'No Data Found'; } return $output; } return view('autosearch'); }
内容的提问来源于stack exchange,提问作者Maher Fakhour
相关产品推荐
相关产品推荐

