wordpress ajax调用上传文件

时间:2015-08-18 14:24:04

标签: jquery ajax wordpress

我正在尝试使用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没有定义。当我尝试&#34; ajax_url&#34;在同一个jquery中定义的变量,它返回&#34; undefined&#34;消息。

此代码中的问题是什么?需要进行哪些修改。请帮帮我。

2 个答案:

答案 0 :(得分: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')。

此外,您应该在jQuery脚本中取消引用字符串,并从模板文件中的表单中删除wp_localize_script行。

答案 1 :(得分:2)

删除

contentType: 'json'

来自jquery并试一试。

我已经阅读过之前的堆栈答案中的某个地方

相关问题