Getting image urls from a directory

元气小坏坏 提交于 2019-12-12 03:09:55

问题


I'm trying to make a slideshow with jQuery, for this I try to get all of the images' urls stored in a folder without having to write them manualy It looks like I have to play around with Ajax, but I'm a bit confused I would basically like to get the var stored in an array in my PHP code

<?php
$dir = "img";
if (is_dir($dir)){
    if ($dh = opendir($dir)){
        $images = array();
        while (($file = readdir($dh)) !== false){
            if (!is_dir($dir.$file)) $images[] = $file;
        }
        closedir($dh);
    }
}
$max = count($images);

So how could I quickly get the values of $images[] in javascript? Anly help would be very appreciated! :)


回答1:


<?php
$dir = "img";
$images = array();
if (is_dir($dir)){
    if ($dh = opendir($dir)){
        while (($file = readdir($dh)) !== false){
            if (!is_dir($dir.$file)) $images[] = $file;
        }
        closedir($dh);
    }
}

header('Content-Type: application/json');
echo json_encode($images);

jQuery will automatically parse the JSON as long as the header content-type is set:

$.ajax({
 'url' : 'imagelist.php',
 'success': function(result) {
   ...
 },
});



回答2:


I'm not an expert at php, but I'm going to assume that $images is an array of filenames. If not, change your code to also do that. Then at the end of your php file, add this:

echo json_encode($images);

Then in javascript, something like this:

$.get('imagelist.php').done(function(result) {
    $.each(result, function(idx, image) {
        console.log('found image: ' + image);
    }
});



回答3:


JS:

<script>
function loadPHP()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","somephp.php",true); //replace this with your file name
xmlhttp.send();
}
</script>

HTML:

<button onclick="loadPHP()">Click to load php</button>
<div id="myDiv"></div>

PHP:

<?php
$dir = "img";
if (is_dir($dir)){
    if ($dh = opendir($dir)){
        $images = array();
        while (($file = readdir($dh)) !== false){
            if (!is_dir($dir.$file)) $images[] = $file;
        }
        closedir($dh);
    }
}
$max = count($images);
$toprint = "<ul>";
foreach($images as $x => $y){
    $toprint .= ("<li>".$y."<br /></li>");
}
echo $toprint;
?>


来源:https://stackoverflow.com/questions/18316208/getting-image-urls-from-a-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!