2016-11-17 56 views
2

我讀了一些SO問題,但沒有什麼可以幫助我。通過jQuery發送圖片到PHP - FormData是每次都是空的

我有一個普通的HTML表單:

<form id="featured_upload" method="post" action="#" enctype="multipart/form-data"> 
    <input type="file" name="my_image_upload" id="my_image_upload" multiple="false" /> 
    <input type="hidden" name="post_id" id="post_id" value="<?php echo get_the_ID(); ?>" /> 
    <?php wp_nonce_field('my_image_upload', 'my_image_upload_nonce'); ?> 
    <div class="button-reg-box"> 
    <button type="submit" class="btn btn-primary btn-set-picture">Profilbild bearbeiten</button> 
    </div> 
</form> 

這是我的jQuery函數:

jQuery('#featured_upload').submit(function (e) { 
    e.preventDefault(); 
    SetAndChangePicture(); 
}); 

function SetAndChangePicture() { 
    var test = new FormData(this); <-- empty :(
    console.log(test); 
    jQuery.ajax({ 
     type: "POST", 
     async: false, 
     url: dmd_output_favorites_obj.ajax_url, 
     data: { 
      action: "dmd_picture", 
      formdata: new FormData() <-- empty too but I want to test above 
     }, 
     success: function (data) { 
      //jQuery('#MemberAreaChangeInterests .alert-success').show(); 
     } 
    }); 
} 

var test = new FormData(this);是每次空。我試過this和窗體的jQuery選擇器。兩者都不起作用。

編輯:在控制檯

錯誤:

Uncaught TypeError: Illegal invocation

編輯:

這是我調試的圖片:

enter image description here

回答

0

試試這個

var formData = $('#featured_upload').serialize(); 

這會給你的表格細節

+0

它仍然是空的。 – cgee

0

嘗試以下操作:

<input type="hidden" name="action" id="post_id" value="dmd_picture" /> 

變化數據添加隱藏與動作輸入類型:

data: new FormData(jQuery('#featured_upload')[0]); 

使用以下ajax屬性

contentType: false, 
processData: false, 

注意:不要使用async:false;

+0

仍然爲空並出現此新錯誤。 Uncaught TypeError:k.toLowerCase不是函數 – cgee

+0

FormData不接受參數的權利? https://developer.mozilla.org/en-US/docs/Web/API/FormData –

+0

什麼是空的?你怎麼知道是空的? – madalinivascu

1

嘗試下面的代碼:

var formData = new FormData(); 
formData.append('image', $('input[type=file]')[0].files[0]); 

發送形式

使用jQuery Ajax請求將看起來像這樣:

$.ajax({ 
    url: 'Your url here', 
    data: formData, 
    type: 'POST', 
    contentType: false, 
    processData: false, 
    //...Other options like success and etc 
}) 
+0

我調試了var formData,但這個var仍然是空的。 – cgee

+0

@cgee應該嘗試刪除SetAndChangePicture粘貼代碼 –