AJAX图像上传到Wordpress

时间:2013-01-18 06:27:39

标签: ajax image wordpress file-upload

所以我试图允许用户从Wordpress网站的前端上传图像。我不希望他们必须注册帐户或任何东西。我正在使用jQuery插件AJAXUpload来处理前端的所有内容,并且它运行良好。但是每当我调用Wordpress的AJAX函数时,我都没有得到任何响应。我已经尝试过简单地输掉一根绳子,但我仍然没有收到任何东西。

这是我在Wordpress后端的代码,它应该接受图片上传。

if( !function_exists( 'ni_handle_file_upload' ) ){
function ni_handle_file_upload() {
    //global $wpdb, $global_contest_settings;
    die(json_encode("test"));
    /*if ($_FILES) {
        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        require_once(ABSPATH . "wp-admin" . '/includes/file.php');
        require_once(ABSPATH . "wp-admin" . '/includes/media.php');

        $attachment_ids = array();
        foreach ($_FILES as $file => $array) {
            // check to make sure its a successful upload
            if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
                die(json_encode(array(
                    "status" => "error",
                    "message" => "There was an error uploading the file."
                )));
            }

            $attachment_ids[] = media_handle_upload( $file );
        }
    }

    die(json_encode(array(
        "status" => "success",
        "message" => "File uploaded successfully",
        "attachment_ids" => $attachment_ids
    )));*/
}
add_action( 'wp_ajax_handle_file_upload', 'ni_handle_file_upload' );
add_action( 'wp_ajax_nopriv_handle_file_upload', 'ni_handle_file_upload' );
}

这是我在前端使用的JS上传文件。

new AjaxUpload('thumb', {
action: Contest.ajaxurl,
name: 'image',
data: {
    action: "handle_file_upload"
},
autoSubmit: true,
responseType: "json",
onSubmit: function(file, extension) {
    $('div.preview').addClass('loading');
},
onComplete: function(file, response) {
    thumb.load(function(){
        $('div.preview').removeClass('loading');
        thumb.unbind();
    });
    thumb.attr('src', response);
}
});

我已经在整个JS中打破了一切,一切都很好,除了onComplete事件永远不会触发,而且我在Chrome的网络选项卡中可以看到它,它会调用Wordpress的admin-ajax.php ,但即使我只运行一行代码,它也永远不会得到回复。我在这里错过了什么?

1 个答案:

答案 0 :(得分:0)

在WordPress中,您需要使用WP_Ajax_Response发回回复。例如:

$response = array(
   'action'=>'handle_file_upload',
   'data'=> array('status' => 'success', 'message' => 'File uploaded successfully',     'attachment_ids' => $attachment_ids)
);

$xmlResponse = new WP_Ajax_Response($response);
$xmlResponse->send();
相关问题