2013-01-18 117 views
0

所以我試圖讓用戶從Wordpress網站的前端上傳圖片。我不希望他們必須註冊一個帳戶或任何東西。我使用jQuery插件AJAXUpload來處理前端的所有內容,並且完美運行。但是,無論何時我調用Wordpress的AJAX函數,我都沒有得到任何答覆。我嘗試過簡單地去掉一個字符串,但我仍然沒有收到任何迴應。AJAX圖片上傳到Wordpress

下面是我在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); 
} 
}); 

我breakpointed整個JS,一切都OK,不同的是,onComplete時間從未火災,從我可以在Chrome網絡選項卡告訴,它使調用出來的WordPress的管理的事實-ajax.php,但即使在我只運行一行代碼時,它也不會得到迴應。我在這裏錯過了什麼?

回答

1

在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();