2016-03-02 62 views
1

當我嘗試從我的LTS服務器不在我的本地計算機)上發送帶有AJAX的FormData時似乎存在問題。我懷疑FormData並不支持所有的瀏覽器,但它可以在我的本地機器上完美地工作,使用我在我的服務器(LTS)上試用過的相同瀏覽器。我在這裏有點迷路,不知道該怎麼做。如何通過AJAX正確發送FormData()

爲了進一步解釋:

指數

<form class="image" enctype="multipart/form-data" accept-charset="utf-8" method="post"> 
    <input id="image-value" data-id="{{id}}" name="{{picture}}" class="image-box-{{id}}" data-type="{{type}}" type="file" value="{{picture}}" /> 
    <p id="{{id}}" class="label" >Update</p> 
</form> 

我需要在這裏得到文件並上傳到服務器目錄

腳本

$('[id="image-value"]').change(function(e) { 

var data = new FormData(); 
var file_data = this.files[0]; 
data.append('file', file_data); 

e.preventDefault(); 
$.ajax({ 
    url: './someController/upload_picture/', 
    type: 'POST', 
    data: data, 
    cache: false, 
    contentType: false, 
    processData: false, 
    dataType: 'json', 
    success: function(data){ 
     if (data.success == true) { 
      console.log(data.image_name); 
     } else { 
      var error = data.error_message; 
      $(".question-message").fadeIn("fast").html(error); 
     } 
    }, 
    error: function(jqXHR, textStatus, errorThrown) { 
     console.error("The following error occured: " + textStatus, errorThrown); 
    } 
}); 

}); 

控制器

function __construct() { 
    parent::__construct(); 
    $config['upload_path'] = './data/picDir/'; 
    $config['allowed_types'] = 'gif|jpg|png|jpeg'; 
    $config['overwrite'] = TRUE; 
    $this->load->library('upload', $config); 
    $this->upload->initialize($config); 
} 
function upload_picture() { 
    if ($this->check_authorization()) { 
     if ($this->ion_auth->get_user_id()) { 
      if ($this->upload->do_upload('file')) { 
       $data = $this->upload->data(); 
       echo json_encode(array(
        "image_name" => $data["file_name"], 
        "success" => true 
       )); 
      } else { 
       echo json_encode(array(
        "success" => false, 
        "error_message" => $this->upload->display_errors() 
       )); 
      } 
     } 
    } 
} 

當觸發時,請求只是在等待來自php控制器的響應,我認爲這不響應。

+0

嘗試從ajax請求中刪除網址中的點,然後重試。 –

+0

我沒有看到我的控制器從URL的目錄有任何問題。當'data:data'沒有通過時,它工作正常 –

回答

0

我相信你的「echo json_encode ...」應該在響應中 - 像$ this-> response(json_encode ...)。 echo不會返回對ajax請求的響應。請檢查您的框架或lib以獲取正確的響應並分享它。

+0

請注意,這在我的本地機器上完美運行。我認爲問題出現在這裏'data = new FormData()' –

+0

可以用不同的方式設置數據並重試 – ArchLicher