0

所以我试图让用户从 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,但它即使我只运行一行代码,也永远不会得到响应。我在这里错过了什么?

4

1 回答 1

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();
于 2013-07-01T16:33:08.227 回答