javascript - 如何遍历本地(服务器端)文件夹的所有元素?

标签 javascript html file-io directory

基本上,我有一个非常简单的网站,其根目录如下所示:

/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 转换在服务器代码和客户端中都有效。

关于javascript - 如何遍历本地(服务器端)文件夹的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13595113/

相关文章:

javascript - 如何将从后端呈现的参数传递给angular2 bootstrap方法

python - 如何在python中使用print语句测试文件写入

javascript - 用 Javascript 创建秒表

javascript - 如何使 POST Action 与 jquery/ajax Colorbox 一起工作? (里面的 fiddle )

html - 似乎无法摆脱我的 CSS 菜单中额外的 1px 白色边框

html - 如何制作粘性标题?

c# - 有没有办法让这个 C# 代码自动覆盖文件?

java - 用户自定义文件读取函数导致NullPointerException Java

javascript - 我可以使用任何版本的 jquery 使用 jQuery.noConflict

php - 如何在jquery中的SELECT查询中传递多个参数?