You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中Ajax生成的HTML路由链接失效问题求助

解决Laravel控制器中Ajax返回的链接失效问题

问题原因

  1. 你在控制器的HTML字符串拼接中使用了Blade模板语法{{route()}},但控制器直接返回纯HTML字符串时,Blade引擎不会解析这些模板语法,导致未处理的代码直接输出。
  2. 字符串拼接存在语法错误:'.$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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:03:15