WordPress Ajax调用上传文件

3

我正在尝试在WordPress中使用Ajax上传文件。

我正在尝试以下表单:

 <form class="form-horizontal" id="file_form">

<?php  wp_nonce_field("ajax_file_nonce","security");  
 wp_localize_script( 'custom-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
 ?>

<input type="hidden" name="action" value="my_file_upload">
<input id="resume" name="resume" class="input-file form-control" type="file">

这是我的函数:

add_action('wp_ajax_my_file_upload', 'my_file_upload');

add_action('wp_ajax_nopriv_my_file_upload', 'my_file_upload');

function handle_file_upload()
{

    $response['message'] = 'Done!';
     echo json_encode($response); die();
     check_ajax_referer('ajax_file_nonce', 'security');

    if(!(is_array($_POST) && is_array($_FILES) && defined('DOING_AJAX') && DOING_AJAX)){
        return;
    }

    if(!function_exists('wp_handle_upload')){
        require_once(ABSPATH . 'wp-admin/includes/file.php');
    }
    $upload_overrides = array('test_form' => false);

    $response = array();

    foreach($_FILES as $file){
        $file_info = wp_handle_upload($file, $upload_overrides);

        // do something with the file info...
        $response['message'] = 'Done!';
    }

    echo json_encode($response);
    die();
}

这是我的 jQuery 代码:

jQuery(document).on(\'click\', \'#send\', function(e){
//alert();
e.preventDefault();
var ajax_url = "'.admin_url('admin-ajax.php').'"
    var form_data = {};
$("#file_form").find(\'input\').each(function(){
    form_data[this.name] = $(this).val();
    //alert(this.name);
    });


jQuery.ajax({
        type: 'POST',
        url: MyAjax.ajaxurl, // 
        data: form_data,
        contentType: 'json',
        success: function(response){
            alert(response.message);
        }
    }); 


 });

但是这显示了MyAjax未定义。当我尝试在同一个jQuery中定义“ajax_url”变量时,它返回“未定义”的消息。

这段代码有什么问题?需要做哪些修改?请帮帮我。


我已经尝试找到所有的示例,并尝试了他们建议的一切,但不知道我漏掉了什么。 - chetan patel
我在这方面没有成功,但我找到了这个插件并为我的使用进行了定制。https://wordpress.org/plugins/alchemist-ajax-upload/ 感谢开发者。 - chetan patel
2个回答

3

这可能取决于您如何加载jQuery脚本以及如何使用wp_localize_script函数。

请在您的functions.php文件中尝试以下内容:

add_action( 'wp_enqueue_scripts', function(){
    wp_enqueue_script( 'custom-ajax-request', get_stylesheet_directory_uri().'/js/custom-ajax-request.js', array('jquery') );
    wp_localize_script( 'custom-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
} );

wp_enqueue_script函数会加载你的jQuery脚本(我将文件命名为custom-ajax-request.js),而wp_localize_script函数则将MyAjax变量传递到该脚本中(确保使用相同的句柄,即在本例中为'custom-ajax-request')。

此外,您应解除引号并删除模板文件中表单中的wp_localize_script行。


错误已解决: "MyAjax 未定义"。但返回值是0,而不是返回 "完成!"。 - chetan patel

2

删除

contentType: 'json'

从 jQuery 开始尝试。

我在之前的 Stack 回答中读到过一些内容。


它可以工作,但是当我尝试打印$_files数组时,它显示为空。我该怎么办? - chetan patel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接