dpwqicw157673 2014-01-01 11:00
浏览 49
已采纳

使用javascript / jquery将图像从php添加到文档中

    <?php
$imgDir =   'images/';
$images =   glob($imgDir . '*.{jpg,jpeg,png,gif}',GLOB_BRACE);
echo json_encode($images);  
?>

<script>
jQuery(function(){
    var phpvar  =   '<?php echo json_encode($images) ?>';
        jQuery('body').append('<img src="' + phpvar + '"/>');
    });
</script>

The top php scans the folder 'images' and echoes all the file pathnames. However i want to use the array formed from this and append it to the document/body to display the images using . But i'm not sure how to pass the php variable '$images' to jquery/javascript

  • 写回答

3条回答 默认 最新

  • douzhanlai4671 2014-01-01 11:26
    关注

    The phpvar that you're creating is actually an array (provided you remove the quotes), so you need to loop through this array and add each image separately, like this:

    jQuery(function(){
        var phpvar = <?php echo json_encode($images) ?>;
        $.each(phpvar, function(id, image){
            jQuery('body').append('<img src="' + image + '"/>');
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题