简体   繁体   English

使用 PUT 方法 AJAX 导致 Laravel 中的 $request->all() 数组为空 6

[英]Using PUT method AJAX results in empty $request->all() array in Laravel 6

I have a very simple form for testing purposes, when I try to PUT the formData using $.ajax I get a empty array response but this happen only when I use PUT method, if I use POST instead of PUT method works as expected.我有一个非常简单的表单用于测试目的,当我尝试使用 $.ajax 放置 formData 时,我得到一个空数组响应,但这仅在我使用 PUT 方法时发生,如果我使用 POST 而不是 PUT 方法按预期工作。

I'm using Laravel 6, I have a var_dump in each function:我正在使用 Laravel 6,我在每个 function 中都有一个 var_dump:

var_dump($request->all())

When I use PUT method I get:当我使用 PUT 方法时,我得到:

array(0) {}

When I use POST method I get:当我使用 POST 方法时,我得到:

array(4) { ["form1"]=> string(1) "1" ["form2"]=> string(1) "2" ["form3"]=> string(1) "3" ["form4"]=> string(1) "4" } 

I need the formData because I going to PUT image files.我需要 formData,因为我要 PUT 图像文件。 I was looking for another similar questions but no one solves my issue.我一直在寻找另一个类似的问题,但没有人解决我的问题。

There are another method to perform this?还有另一种方法可以执行此操作吗?


<form id="formTest" type="multipart/form-data">
    <input name="form1" value="1">
    <input name="form2" value="2">
    <input name="form3" value="3">
    <input name="form4" value="4">
    <button type="submit">Accept</button>
</form>

<script>
    $(document).ready(function () {
        $('#formTest').on('submit', function (e) {

            e.preventDefault();

            var formData = new FormData($(this)[0]);

            $.ajax({
                url: '<?echo($config->get('apiUrl'))?>movies/13',
                type: 'PUT',
                processData: false,
                contentType: false,
                data: formData,
                success: function(result)
                {
                },
                error: function(data)
                {
                    console.log(data);
                }
            });
        });

    });
</script>

Try adding these two input fields in your form.尝试在表单中添加这两个输入字段。

<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">

The first one is changed the form submission method to "PUT" and the second one is including the CSRF Token to the form.第一个是将表单提交方法更改为“PUT”,第二个是将 CSRF Token 包含到表单中。

Then in your AJAX code, change the type: 'PUT' to type: 'POST' .然后在您的 AJAX 代码中,将type: 'PUT'更改为type: 'POST'

$.ajax({
    url: '<?echo($config->get('apiUrl'))?>movies/13',
    type: 'POST',
    processData: false,
    contentType: false,
    data: formData,
    success: function(result) {},
    error: function(data) {
        console.log(data);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM