2016-11-07 118 views
4

我的java腳本。我想顯示圖像。 javascript需要圖像路徑爲數組格式。我試圖提供路徑拋出ajax。它不工作。當我使用硬編碼工作。我的javascipt下面。它不工作。在JavaScript和我的PHP文件代碼下面的工作代碼供應也在那裏。如何將數組從php(使用json_encode)傳遞給javascript

$(function() { 
    $.get("php/building_edit_image_get_db.php", function(your_return_data) { 
    alert(your_return_data); 

     $("#editimagefile").fileinput({ 
      showUpload: false, 
      showCaption: false, 
      overwriteInitial: true, 
      initialPreview: [your_return_data], 
      initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup 
      initialPreviewFileType: 'image', // image is the default and can be overridden in config below 
      browseClass: "btn btn-primary btn-lg", 
      allowedFileExtensions : ['jpg', 'png','gif'] 
     }); 
    }); 
}); 

這不起作用。當我把硬編碼其正常工作的腳本是低於

$(function() { 
    $.get("php/building_edit_image_get_db.php", function(your_return_data) { 
    alert(your_return_data); 

     $("#editimagefile").fileinput({ 
      showUpload: false, 
      showCaption: false, 
      overwriteInitial: true, 
      initialPreview: [ 
       "http://lorempixel.com/800/460/people/1", 
       "http://lorempixel.com/800/460/people/2" 
      ], 
      initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup 
      initialPreviewFileType: 'image', // image is the default and can be overridden in config below 
      browseClass: "btn btn-primary btn-lg", 
      allowedFileExtensions : ['jpg', 'png','gif'] 
     }); 
    }); 
}); 

我的PHP文件returing數組值。

session_start(); 
require_once ('../aiboc_admin/class/Buidling_Image.php'); 

$editid = $_SESSION['BUILD_LIST_EDIT_ID']; 

$getimgs = Buidling_Image::GetGalleryImageByID($editid); 

    foreach ($getimgs as $setimgs) 
    { 
     $imgs[] = $setimgs['img_url']; 
    } 
echo json_encode($imgs,JSON_UNESCAPED_SLASHES); 

回答

2

你應該使用$.parseJSON()因爲你得到JSON格式當您使用json_encode

$.get("php/building_edit_image_get_db.php", function(your_return_data) { 

    $("#editimagefile").fileinput({ 
     showUpload: false, 
     showCaption: false, 
     overwriteInitial: true, 

     initialPreview: $.parseJSON(your_return_data), 

     initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup 
     initialPreviewFileType: 'image', // image is the default and can be overridden in config below 
     browseClass: "btn btn-primary btn-lg", 
     allowedFileExtensions : ['jpg', 'png','gif'] 
    }); 

}); 

或者你可以使用$.getJSON()代替$.get()要求,那麼你不需要對它進行解析:

$.getJSON("php/building_edit_image_get_db.php", function(your_return_data) { 

希望這會有所幫助。