【问题标题】:Posting data with jQuery in Wordpress succeeds, but fails with FormData在 Wordpress 中使用 jQuery 发布数据成功,但使用 FormData 失败
【发布时间】:2021-02-10 04:07:37
【问题描述】:

我想在我的 Wordpress 插件中使用 jQuery/Ajax 上传文件。 javascript 到 PHP 调用有效。所以接线等工作。但是,一旦我发布了发布文件所必需的 formData,我就不再使用 PHP 函数了。

JavaScript,

        var doesntWork = new FormData();
        doesntWork.append('file', 'a name');

        var withthisItWorks = 'text'

        var data = {
            'action': 'emfi_file_upload',
            'data': doesntWork
        }

        $.ajax({
            type: "POST",
            url: ajax_object.ajaxurl,
            data: data,
            success: function(response) {
                jQuery('#emfi-message').html(`<span style="color: green;">Respons: ${response}</span>`);
            }
        });

PHP 函数只返回一个字符串答案:

function emfi_file_upload_callback() {
    echo 'Yes, in the callback';
    wp_die();
}

当我将纯文本放入数据对象时,我会从 PHP 函数中得到答案。当我把formData放进去时,没有答案。我在互联网上尝试了很多示例,但每次都归结为这一点。添加 contentType: false 和 processData: false,正如在其他地方提到的,没有帮助。怎么了?

【问题讨论】:

    标签: javascript php jquery wordpress file-upload


    【解决方案1】:

    发送的所有字段都必须在 formdata 对象中。
    此外,要让 FormData 与 jQuery.ajax 一起使用,processDatacontentType 必须设置为 false。

        var doesWork = new FormData();
        doesWork.append('file', someFile);
        doesWork.append('action', 'emfi_file_upload');
      
        $.ajax({
            type: "POST",
            url: ajax_object.ajaxurl,
            data: doesWork,
            contentType: false,
            processData: false,
            success: function(response) {
                jQuery('#emfi-message').html(`<span style="color: green;">Respons: ${response}</span>`);
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-28
      • 2015-11-18
      • 2016-07-15
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 1970-01-01
      相关资源
      最近更新 更多