使用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
答
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 + '"/>');
});
});
答
<?php
$imgDir = 'images/';
$images = glob($imgDir . '*.{jpg,jpeg,png,gif}',GLOB_BRACE);
$image_var ="";
foreach($images as $img)
{
$image_var.="<img src=".$img.">";
}
echo json_encode($image_var);
?>
<script>
jQuery(function(){
var phpvar = <?php echo json_encode($image_var) ?>;
jQuery('body').append(phpvar);
});
</script>
答
In my opinion you are wasting processing and a needless framework for simple PHP array processing.
No need for either JSON, JSONEncode or jQuery:
foreach (glob('images/*.{jpg,jpeg,png,gif}',GLOB_BRACE) as $filename) {
echo '<img src=".$filename.'" alt="" />'."
";
}