当库本身使用 POST 时,如何在 jQuery/JS 中发送 DELETE 请求?

How to send DELETE request in jQuery/JS when the library itself uses POST?

我正在使用 Kartik-v/file-input 或称为 Boostrap 文件输入,我想删除上传的图像。

docs 中,我提供了服务器上存储的图像的删除 URL。这些删除 URL 是 API,并且正在接受 DELETE 请求。但是,url 正在发送 POST 请求,然后我的 Laravel 抛出一个异常:

The POST method is not supported for this route. Supported methods: GET, HEAD, PUT, PATCH, DELETE.

我该如何解决这个问题?如何让 url: 发送 DELETE 请求而不是 POST?

$('.uploaded-images').fileinput({
        browseLabel: 'Browse',
        browseIcon: '<i class="icon-file-plus mr-2"></i>',
        uploadIcon: '<i class="icon-file-upload2 mr-2"></i>',
        initialPreview: [
            'image/an-example-image.png',
            'image/an-example-image2.png',
        ],
        initialPreviewConfig: [
            {caption: 'Jane.jpg', key: 1, url: 'http://web.com/api/medias/14', showDrag: false},
            {caption: 'Anna.jpg', key: 2, url: '{$url}', showDrag: false}
        ],
        initialPreviewAsData: true,
        overwriteInitial: false,
        maxFileSize: 1000,
    });

尝试在您的表单中包含以下隐藏输入字段,然后发送请求,同时您的表单提交类型为 POST

<input type="hidden" name="_method" value="delete" />

The POST method is not supported for this route. Supported methods: GET, HEAD, PUT, PATCH, DELETE.

Laravel 需要将额外信息添加到他们的表单中才能正确发送 DELETE 请求。

如果您使用的是 Blade 模板,那么它看起来像:

{{ Form::open(['url' => 'foo/bar', 'method' => 'delete', 'class' => 'deleteForm']) }}
  <input type="submit" class="deleteBtn" />
{{ Form::close() }}

如果您不使用 Blade 模板,请在声明表单后立即添加以下内容之一(在 HTML 中):

{{ Form::hidden('_method', 'DELETE') }}

{{ method_field('DELETE') }}

您可以在 laravel here, and here

中详细了解 DELETE 请求

我也看到你的评论提到:

I'm using that kartik-v/file-input plugin and it provide delete button

我以前从未使用过该插件;但也许您可以 edit/modify 通过将按钮封装在表单中来正确发送 DELETE 请求的按钮?

例如:

<form method="POST" action="/admin/users/{{$user->id}}">
        {{ csrf_field() }}
        {{ method_field('DELETE') }}

        <-- Your Delete Button/Input field Here -->
</form>

根据 source of the library and its docs 判断。您可以将请求方法作为 jquery ajax 选项提供给它的选项:ajaxDeleteSettings。例子

$('.uploaded-images').fileinput({
    browseLabel: 'Browse',
    browseIcon: '<i class="icon-file-plus mr-2"></i>',
    uploadIcon: '<i class="icon-file-upload2 mr-2"></i>',
    initialPreview: [
        'image/an-example-image.png',
        'image/an-example-image2.png',
    ],
    initialPreviewConfig: [
        {caption: 'Jane.jpg', key: 1, url: 'http://web.com/api/medias/14', showDrag: false},
        {caption: 'Anna.jpg', key: 2, url: '{$url}', showDrag: false}
    ],
    initialPreviewAsData: true,
    overwriteInitial: false,
    maxFileSize: 1000,
    ajaxDeleteSettings: {
        type: 'DELETE' // This should override the ajax as $.ajax({ type: 'DELETE' })
    }
});

您还可以在定义上述代码段之前在某处全局定义选项。

$.fn.fileinput.defaults.ajaxDeleteSettings = {
    type: 'DELETE'
};