Laravel中的DELETE Ajax请求出现405(Method Not Allowed)错误

时间:2017-10-01 10:17:27

标签: ajax laravel sweetalert

我知道有几篇关于使用AJAX删除的405个错误的帖子。但是,我发现的帖子中没有一个解决方案对我有用。

我有一个包含显示数据库表中所有产品的表的视图。在每一行都有一个删除按钮来删除产品,如下所示:

{!! Form::open(['method' => 'DELETE', 'route' => ['slider.destroy', $slide->id]]) !!}
    <button type="button" class="deleteproductModal btn btn-xs btn-default btn-flat"
            data-toggle="modal"
            data-product_token="{{ csrf_token() }}"
            data-product_name="{{ $slide->title_slider }}"
            data-product_destroy_route="{{ route('slider.destroy', $slide->id) }}">
        <i class="fa fa-trash"></i>
    </button>
{!! Form::close() !!}

点击按钮,执行以下javascript,调用控制器中的destroy方法从数据库中删除产品:

$('button.deleteproductModal').click(function()
{
    var productRoute = $(this).attr("data-product_destroy_route");
    var productName = $(this).attr("data-product_name");
    var productToken = $(this).attr("data-product_token");
    deleteproduct(productRoute, productToken, productName);
});

function deleteproduct(productRoute, productToken, productName)
{
    swal({
        title: "Window product Deletion",
        text: "Are you absolutely sure you want to delete " + productName + "? This action cannot be undone." +
        "This will permanently delete " + productName + ", and remove all collections and materials associations.",
        type: "warning",
        showCancelButton: true,
        closeOnConfirm: false,
        confirmButtonText: "Delete " + productName,
        confirmButtonColor: "#ec6c62"
    }, function()
    {
        $.ajax({
            type: "DELETE",
            url: productRoute,
            headers: { 'X-CSRF-TOKEN' : productToken }
        })
            .done(function(data)
        {
            swal("Window Product Deleted!", productName + " Window Product was successfully delete.", "success");
        })

            .error(function(data)
        {
            swal("Oops", "We couldn't connect to the server!", "error");
        });

    });
}

我的控制器是资源控制器。这是路线:

Route::resource('slider','Backend\SliderController');

这是来自控制器的destroy方法。

public function destroy($id)
{
    $home= Slider::find($id);

    unlink($home->featured_image);

    $home->delete();
    notify()->flash('<h3>Deleted successfully</h3>', 'success', ['timer'=>2000]);
    return redirect('slider');

}

当我删除产品时,我得到oops,我们无法连接到服务器甜蜜警报错误,但当我新鲜页面数据被删除....任何帮助?

1 个答案:

答案 0 :(得分:4)

您必须设置ajax类型 POST ,但发送一个名为_method的参数,其值为delete,如下所示:

$.ajax({
        type: "POST",
        data:{
         _method:"DELETE"
        },
        url: productRoute,
        headers: { 'X-CSRF-TOKEN' : productToken }
    });

或者因为你使用了laravel html表单助手,所以它会自动生成_method隐藏输入,这样你就可以更好地发送所有表单输入,例如令牌和方法,如下所示:

 function()
{

    var formData=$('#yourForm').serialize();
    $.ajax({
        type: "POST",
        url: productRoute,
        data:formData
    })
      .
      . 

});