[英]HTML/Javascript: Iterate through all elements of local (server-side) folder
基本上,我有一個非常簡單的網站,其根目錄如下所示:
/images/
index.html
stuff.js
我想通過某種方式遞歸遍歷/ images /目錄中的每個文件,並按照我網站的一部分順序顯示它們。 例如,如果/ images /包含:
images/a/a.png
images/b.png
images/c.jpg
....
然后index.html中的某個地方將包含:
<img src="images/a/a.png" />
<img src="images/b.png" />
<img src="images/c.jpg" />
....
我的第一個想法是使用stuff.js中的document.write()函數執行此操作,但我找不到在Javascript中迭代本地文件目錄的好方法。 我看到了一些關於AJAX的內容,但所有這些示例都涉及編輯現有文件,我顯然不想這樣做。
我目前的解決方案只是手動創建一個包含/ images /中所有文件的字符串數組,但這樣做讓我覺得“必須有更好的方法!”
如果我不清楚,請告訴我。
謝謝!
也許最好的方法是使用服務器端語言為您執行此操作,並使用異步Javascript請求來顯示數據。
此示例使用PHP列出指定目錄中的所有文件,使用xmlhttprequest
加載此輸出並將結果轉換為圖像標記:
getimages.php:
<?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相同的目錄):
<!DOCTYPE html>
<html>
<head>
<title>Image List Thing</title>
</head>
<body>
<div id="images"></div>
<input type="button" onclick="callForImages()" value="Load" />
<script>
//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);
}
}
</script>
</body>
</html>
請注意,這只是一個例子。 您可能希望確保AJAX調用成功,並且JSON轉換在服務器代碼和客戶端上都有效。
我偶然發現了這篇文章,因為我正在尋找相同的東西,如何遍歷“Resources”文件夾中的文件列表,並顯示一個網頁,其中包含每個文件的可點擊快捷方式。
這是我最終得到的網頁的剪輯:
這就是我做到的。
我添加了一個非常簡單的ASP.Net服務,來迭代這個文件夾中的文件......
List<OneResourceFile> listOfFilenames = new List<OneResourceFile>();
string Icon = "";
string localFolder = Server.MapPath("../Resources");
string[] fileEntries = Directory.GetFiles(localFolder);
foreach (string fileName in fileEntries)
{
string filename = System.IO.Path.GetFileName(fileName);
switch (Path.GetExtension(filename).ToLower())
{
case ".pptx":
case ".ppt":
Icon = "cssPowerPoint";
break;
case ".doc":
case ".docx":
Icon = "cssWord";
break;
case ".xlsx":
case ".xlsm":
case ".xls":
Icon = "cssExcel";
break;
default:
Icon = "cssUnknown";
break;
}
OneResourceFile oneFile = new OneResourceFile()
{
Filename = filename,
IconClass = Icon,
URL = "../Resources/" + filename
};
listOfFilenames.Add(oneFile);
}
string JSON = JsonConvert.SerializeObject(listOfFilenames);
return JSON;
..它構建了一個OneResouceFile
記錄列表,每個記錄都有一個文件名,一個CSS類,用於應用於該快捷方式(可以給它,例如Excel圖標,PDF圖標等)和項目的完整URL。
public class OneResourceFile
{
public string Filename { get; set; }
public string IconClass { get; set; }
public string URL { get; set; }
}
..並返回了一組像這樣的JSON結果......
[
{
Filename: "Mikes Presentation.pptx",
IconClass: "cssPowerPoint",
URL: "~/Resources/Mikes Presentation.pptx"
},
{
Filename: "Mikes Accounts.xlsx",
IconClass: "cssExcel",
URL: "~/Resources/Mikes Accounts.xlsx""
}
]
然后,我得到一些JQuery來調用這個Web服務,並為結果中的每個項創建a href
:
<script type="text/javascript">
var URL = "/GetListOfResourceFiles.aspx"; // This is my web service
$.ajax({
url: URL,
type: 'GET',
cache: false,
dataType: "json",
success: function (JSON) {
// We've successfully loaded our JSON data
$.each(JSON.Results, function (inx) {
// Create one <a href> per JSON record, and append it to our list.
var thelink = $('<a>', {
text: this.Filename,
title: this.Filename,
href: this.URL,
class: this.IconClass
}).appendTo('#ListOfResources');
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert("$.ajax error: " + xhr.status + " " + thrownError);
}
});
</script>
<p id="ListOfResources">
您只需要為cssPowerPoint
, cssExcel
等添加一些CSS樣式,以給出a href
sa相關圖標,例如:
.cssPowerpoint
{
vertical-align: top;
text-align: center;
background-repeat: no-repeat;
background-position: center 5px;
background-image: url(/Images/Icons/icnPowerPoint.png);
width: 100px;
height: 60px;
padding-top: 60px;
text-decoration: none;
display:inline-block;
color: #666;
margin-left: 20px;
}
就是這樣。 很酷,嘿?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.