5

基本的に、ルートディレクトリが次のようになっている非常に単純なWebサイトがあります。

/images/
index.html
stuff.js

/ images /ディレクトリ内のすべてのファイルを再帰的に繰り返し処理し、Webサイトのセクションに順番に表示する方法が必要です。たとえば、/ 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 /内のすべてのファイルを含む文字列の配列を手動で作成することですが、これを行うと、「もっと良い方法が必要だ」と思います。

不明な点がある場合はお知らせください。

ありがとう!

4

2 に答える 2

6

おそらく、これを行うための最良の方法は、サーバー側の言語を使用してそれを行い、非同期の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変換がサーバーコードとクライアントの両方で機能することを確認する必要があります。

于 2012-11-27T23:35:04.570 に答える
1

同じことを探していたので、この記事に出くわしました。「リソース」フォルダ内のファイルのリストを繰り返し処理し、各ファイルへのクリック可能なショートカットを含むWebページを表示する方法です。

これが私が最終的に作ったウェブページのクリップです:

ここに画像の説明を入力してください

これが私がそれをした方法です。

このフォルダー内のファイルを反復処理するために、非常に単純な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""
    }
]

次に、このWebサービスを呼び出すJQueryを取得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">

次に必要なのは、、などのCSSスタイルを追加cssPowerPointして、 saに関連するアイコンcssExcelを与えることです。次に例を示します。a href

.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;
}

以上です。かっこいい、ねえ?

于 2015-07-02T07:16:22.113 に答える