在Wordpress中上传Ajax文件 - 无法传递FormData

Ste*_*fan 10 php ajax wordpress jquery file-upload

我创建了一个脚本,它使用$ .ajax和FormData将两个表单对象传递给PHP.一个表单对象是文本,另一个是文件.它作为一个独立的脚本运行良好.但是,在我将它添加到Wordpress后,作为一个插件,它一直在给我"Uncaught TypeError: Illegal invocation".

我不能序列化formdata,因为那时我将无法将文件传递给PHP中的回调函数.

JS在ajax调用之前涉及FormData:

var fd = new FormData();
var file = jQuery(this).find('input[type="file"]');
var caption = jQuery(this).find('input[name=img_caption]');
var individual_file = file[0].files[0];
fd.append("file", individual_file);
var individual_capt = caption.val();
fd.append("caption", individual_capt);
Run Code Online (Sandbox Code Playgroud)

以上部分是100%正确的.

Ajax调用:

jQuery.ajax({
    type: 'POST',
    url: fiuajax.ajaxurl,
    data: {
        action: 'fiu_upload_file',
        security: fiuajax.security,
        data: fd,
        contentType: false,
        processData: false,
    },
    success: function(response){
        var dataObj = jQuery.parseJSON(response);
        if(dataObj.message == 'error') {
            jQuery('.fiu_validation').html('The following error occured: '+dataObj.desc);
        }
        else if(dataObj.message == 'success') {
            jQuery('.fiu_file').val('');
        }
        console.log(response);
    }
});
Run Code Online (Sandbox Code Playgroud)

这非常令人沮丧,因为它在Wordpress之外工作得非常好.我已经尝试取消注册Wordpress的jQuery并排队最新的jQuery版本,但它没有任何区别.

回顾一下:
1)Ajax/jQuery拒绝将表单对象传递给PHP
2)无法序列化对象,因为我需要保留文件对象
3)脚本在Wordpress之外工作
4)尝试更新到最新的jQuery版本,没变

Dav*_*vid 31

试试这个 :

jQuery(document).on('click', '#submit', function(e){
    e.preventDefault();

    var fd = new FormData();
    var file = jQuery(document).find('input[type="file"]');
    var caption = jQuery(this).find('input[name=img_caption]');
    var individual_file = file[0].files[0];
    fd.append("file", individual_file);
    var individual_capt = caption.val();
    fd.append("caption", individual_capt);  
    fd.append('action', 'fiu_upload_file');  

    jQuery.ajax({
        type: 'POST',
        url: fiuajax.ajaxurl,
        data: fd,
        contentType: false,
        processData: false,
        success: function(response){

            console.log(response);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

PHP

function fiu_upload_file(){

    var_dump($_FILES);
    exit();
}

add_action('wp_ajax_fiu_upload_file', 'fiu_upload_file');
add_action('wp_ajax_nopriv_fiu_upload_file', 'fiu_upload_file');
Run Code Online (Sandbox Code Playgroud)

  • 好吧,0意味着你没有把exit(); 在你的PHP函数....现在在wp安装上测试上面的代码并看到最新消息. (2认同)