php遍历html的list,HTML / Javascript:遍历本地(服务器端)文件夹的所有元素

也许最好的方法是使用服务器端语言为您执行此操作,并使用异步Javascript请求来显示数据.

此示例使用PHP列出指定目录中的所有文件,使用xmlhttprequest加载此输出并将结果转换为图像标记:

getimages.php:

//The directory (relative to this file) that holds the images

$dir = "Images";

//This array will hold all the image addresses

$result = array();

//Get all the files in the specified directory

$files = scandir($dir);

foreach($files as $file) {

switch(ltrim(strstr($file, '.'), '.')) {

//If the file is an image, add it to the array

case "jpg": case "jpeg":case "png":case "gif":

$result[] = $dir . "/" . $file;

}

}

//Convert the array into JSON

$resultJson = json_encode($result);

//Output the JSON object

//This is what the AJAX request will see

echo($resultJson);

?>

index.html(与getimages.php相同的目录):

Image List Thing

//The div element that will contain the images

var imageContainer = document.getElementById("images");

//Makes an asynch request, loading the getimages.php file

function callForImages() {

//Create the request object

var httpReq = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");

//When it loads,

httpReq.onload = function() {

//Convert the result back into JSON

var result = JSON.parse(httpReq.responseText);

//Show the images

loadImages(result);

}

//Request the page

try {

httpReq.open("GET", "getimages.php", true);

httpReq.send(null);

} catch(e) {

console.log(e);

}

}

//Generates the images and sticks them in the container

function loadImages(images) {

//For each image,

for(var i = 0; i < images.length; i++) {

//Make a new image element, setting the source to the source in the array

var newImage = document.createElement("img");

newImage.setAttribute("src", images[i]);

//Add it to the container

imageContainer.appendChild(newImage);

}

}

请注意,这只是一个例子.您可能希望确保AJAX调用成功,并且JSON转换在服务器代码和客户端上都有效.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值