我的java脚本。我想显示图像。 javascript 需要图像路径作为数组格式。我试图提供抛出ajax的路径。它不工作。当我使用硬编码时它的工作。我的 javascipt 下面。它不工作。工作代码在 javascript 下方提供,我的 php 文件代码也在那里。
$(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 文件。
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);
最佳答案
你应该使用 $.parseJSON()
因为当你使用 json_encode
时你得到的是 json 格式:
$.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 ) {
希望这对您有所帮助。
关于javascript - 如何将数组从 php(使用 json_encode)传递到 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40462327/