Laravel Ajax请求成功后如何携带ID重定向到指定路由
Laravel Ajax跳转URL错误问题解决
问题场景
在Laravel后端开发中,创建新客户端后会返回其ID,希望在Ajax请求成功后利用该ID跳转到client/{id}格式的页面(比如client/15),但尝试的前端代码生成了错误URL:client/%27+response.id+%27。
错误代码(前端)
$.ajax({ method: "POST", url: '{{ route('add-new-client') }}', data: { shop_name: shop_name }, success: function(response) { console.log(response); $("#addClientModal").modal("hide"); // 尝试跳转但生成错误URL window.location.href = '{{ route("client", ["id" => "' + response.id + '"]) }}'; }, error: function(error) { console.error(error); } });
错误原因
Blade模板的{{ route() }}是服务器端渲染语法,页面加载时就会执行并生成URL。而response.id是Ajax请求成功后才会得到的客户端变量,服务器端无法识别这个变量,直接把字符串' + response.id + '当作ID参数传入,最终URL被编码后就出现了%27+response.id+%27这类错误内容。
已验证的解决方法(后端返回完整URL)
在后端创建客户端的方法中,直接生成完整的跳转URL并通过JSON返回给前端,前端直接使用该URL跳转:
public function xxx(Request $request) { // ... 客户端创建逻辑 ... return response()->json([ 'url' => url(action([ClientController::class, 'index'], ['id' => $shop->id])), 'success' => 'Shop byl úspěšně vytvořen.' ]); }
前端对应修改success回调:
success: function(response) { console.log(response); $("#addClientModal").modal("hide"); window.location.href = response.url; }
另一种前端拼接方案
如果不想在后端处理URL,也可以先让Blade生成带占位符的基础URL,再用客户端变量替换占位符:
success: function(response) { console.log(response); $("#addClientModal").modal("hide"); // 先生成带占位符的URL,再替换为实际ID const baseUrl = '{{ route("client", ["id" => "PLACEHOLDER"]) }}'; window.location.href = baseUrl.replace('PLACEHOLDER', response.id); }
内容的提问来源于stack exchange,提问作者Dan Rais
相关产品推荐
相关产品推荐

