如何在Laravel中使用Ajax调用删除路由?
如何在Laravel中使用Ajax调用删除路由?
我想用Ajax调用路由资源,当我将type设置为delete时,我遇到了错误(异常\"Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException\")和给出的消息(消息\"The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST.\")。函数几乎工作,因为刷新后状态也会改变,但我遇到了以上错误。\n路由:\nRoute::resource(\'category\', ArtistCategoryController::class);
\n控制器:\n
public function destroy($id) { $category = ArtistCategory::findOrFail($id); $deleteResponse = $category->update([ 'status'=>'d' ]); if ($deleteResponse) { deleteMessage(); return redirect()->back(); } else { errorMessage(); } }
\n视图:\nid}} >
\nAjax:\n
问题的原因是在使用Ajax调用删除路由时,需要在请求的头部设置CSRF令牌。解决方法是在页面底部的文档中查看文档,并创建一个带有令牌的meta标签,并像下面这样获取它:
<meta name="csrf-token" content="{{ csrf_token() }}">
然后,将其设置为Ajax的全局默认值,如下所示:
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
在扩展页面中设置了带有令牌的meta标签<meta name="csrf-token" content="{{ csrf_token()}}"/>。
问题出现的原因是在destroy方法中使用了return redirect()->back();
语句,导致出现错误并且不可接受。解决方法是对destroy方法进行修改,将返回值类型改为\Illuminate\Http\JsonResponse,并使用response()->json()
方法返回JSON格式的响应数据。修改后的代码如下:
public function destroy($id): \Illuminate\Http\JsonResponse { $category = ArtistCategory::findOrFail($id); $deleteResponse = $category->update([ 'status'=>'d' ]); if ($deleteResponse) { return response()->json([ 'data' => [ 'id' => $id ], 'status' => 'success', ]); } else { return response()->json([ 'data' => [ 'id' => $id ], 'status' => 'error', 'message' => __("Couldn't Delete. Please Try Again!") ], 500); } }