Jquery.ajax PUT 数据未被 PHP 解析

Jquery.ajax PUT data not parsed by PHP

我正在使用 Slim PHP 框架,并尝试通过以下方式使用 Jquery.ajax() 发送 FormData:

var data = new FormData();
data.append('some_name', 'some_data');
data.append('a_file', $('input[name=the_file_form_field]').get(0).files[0]));

$.ajax({
    url: 'the_destination_url',
    data: data,
    processData: false,
    contentType: false,
    type: 'PUT',
    dataType: 'json',

    success: function(data, textStatus, jqXHR) {
        //Processing result here
    },

    error: function(jqXHR, textStatus, errorThrown) {
        //Processing result here
    }
});

不过,我尝试了以下场景:

有什么我遗漏的吗?

应用程序要求它使用 PUT 请求,因此 POST 请求是不可能的。

尝试将数据作为对象发送。 例如

data: {'formData' : data},

您的 Ajax 请求应该如下所示

$.ajax({
    url: 'the_destination_url',
    data: {'formData' : data},
    processData: false,
    contentType: false,
    type: 'PUT',
    dataType: 'json',

    success: function(data, textStatus, jqXHR) {
        //Processing result here
    },

    error: function(jqXHR, textStatus, errorThrown) {
        //Processing result here
    }
});

我使用发帖人的评论解决了这个问题:https://bugs.php.net/bug.php?id=26004

显然,只要超过 post_max_size 指令,PHP 就会悄悄丢弃所有传入的 POST 数据。

除了 post_max_size 之外,检查 upload_max_filesize 指令也很明智。

在PHP中获取从AjaxJQuery发送的PUT数据的最佳方法是:

像这样在 JavaScript 中发送您的数据:

where mydata is {k1 : "val1" , "k2" : "val2" , }

 $.ajax({
     url: "data.php",
     contentType : "json",
     data : mydata,
     method:"PUT",
     success: function (data) {
         console.log(data);
     },
     error: function (err) {
         console.log(err);
     },
     complete:function (e) {
         console.log(e);
     }
 });

获取data.php文件中数据的方法是:

parse_str(file_get_contents("php://input"),$putVars);
var_dump( $putVars ); // input from your form