如何将数组从php(使用json_encode)传递给javascript

时间:2016-11-07 09:58:04

标签: javascript php jquery

我的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);

1 个答案:

答案 0 :(得分:2)

您应该使用$.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 ) {

希望这有帮助。

相关问题