微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

希望这可以帮助.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐