2017-04-17 66 views
0

我張貼的圖像中從我的形式的陣列使用AJAX,並且響應我收到了JSON數據打印JSON數據轉換成HTML格式

我接收到下面的代碼在我的控制檯作爲響應;

0"C:\xampp\htdocs\3Dklik\..../1492427792slider_7.jpg" 
1"C:\xampp\htdocs\3Dklik\mog/1492427792slider_2.jpg" 
2"C:\xampp\htdocs\3Dklik\mo…../public/img/1492427792" 
id"" 
user_id"1" 

以下是我AJAX代碼:

<script type="text/javascript"> 
    $(document).ready(function(e) { 
     $("#btnsubmit").on('click', function(e) { 
      e.preventDefault(); 
      var formData = $('#uploadform').serialize(); 
      var files = $("#uploadform")[0]; 
      console.log(files); 
      $.ajax({ 
       url: '<?php echo $this->url(' 
       upload ');?>', 
       type: 'POST', 
       data: new FormData(files), 
       xhr: function() { 
        var myXhr = $.ajaxSettings.xhr(); 
        return myXhr; 
       }, 
       success: function(data) { 
        alert("Data Uploaded: " + data); 
        console.log(data); 
       }, 
       error: function(result) { 
        alert("Error"); 
       }, 

       cache: false, 
       contentType: false, 
       processData: false 
      }); 
      return false; 
     }); 
    }); 
</script> 

而下面是我PHP代碼;

public function uploadAction() { 
    $request = $this - > getRequest(); 
    if ($request - > isPost()) { 
     $data = array_merge_recursive(
      $request - > getPost() - > toArray(), 
      $request - > getFiles() - > toArray() 
     ); 
     // echo'<pre>';print_r($data); 
    } 
    $image_array = array_slice($data, 2); 
    //print_r($image_array); 
    foreach($image_array as $files) { 
     //print_r($files); 
     $file_new_name = round(microtime(true)).$files['name']; 
     $destination = "public/img/".$file_new_name; 
     $file_name = $files['tmp_name']; 
     move_uploaded_file($file_name, $destination); 
     $data[] = __DIR__.('/../../../../../public/img/').$file_new_name; 
    } 
    return new JsonModel(array(
     'data' => $data 
    )); 
} 

基本上JSON數據包括圖像路徑,但我希望在我<div>以顯示圖像。我怎樣才能做到這一點?

回答

0

你可以使用JSON格式,如validate.php;

echo json_encode(arrayvalue);

$("#btnsubmit").on('click', function(e) { 
    e.preventDefault(); 
    var formData = $('#uploadform').serialize(); 
    var files = $("#uploadform")[0]; 
    console.log(files); 
    $.ajax({ 
     url: '<?php echo $this->url(' 
     upload ');?>', 
     type: 'POST', 
     data: new FormData(files), 
     dataType: 'json', 
     xhr: function() { 
      var myXhr = $.ajaxSettings.xhr(); 
      return myXhr; 
     }, 
     success: function(data) { 
      alert("Data Uploaded: " + data); 
      console.log(data); 
      $.each(data, function(i, item) { 
       alert(data[i].imgName); 
      }); 
     }, 
     error: function(result) { 
      alert("Error"); 
     }, 
     cache: false, 
     contentType: false, 
     processData: false 
    }); 
    return false; 
}); 
+0

我怎樣才能得到imgName? – piyuu

+0

你可以發送數據 $ this-> url('upload');在文件數組中('id'=> 1,'imgname'=>'somename');你可以使用json_encode(array); –