如何使用Jquery/Javascript将文件夹中的所有图像加载到web页面中

时间:2022-01-24 07:19:24

I have a folder named "images" in the same directory as my .js file. I want to load all the images from "images" folder into my html page using Jquery/Javascript.

我在.js文件所在的目录中有一个名为“images”的文件夹。我想使用Jquery/Javascript将来自“images”文件夹的所有图像加载到我的html页面中。

Since, names of images are not some successive integers, how am I supposed to load these images?

因为,图像的名称不是一些连续的整数,我该如何加载这些图像呢?

12 个解决方案

#1


49  

Use :

使用:

var dir = "Src/themes/base/images/";
var fileextension = ".png";
$.ajax({
    //This will retrieve the contents of the folder if the folder is configured as 'browsable'
    url: dir,
    success: function (data) {
        //List all .png file names in the page
        $(data).find("a:contains(" + fileextension + ")").each(function () {
            var filename = this.href.replace(window.location.host, "").replace("http://", "");
            $("body").append("<img src='" + dir + filename + "'>");
        });
    }
});

If you have other extensions, you can make it an array and then go through that one by one using in_array().

如果有其他扩展,可以将其设置为数组,然后使用in_array()逐个遍历该扩展。

P.s : The above source code is not tested.

P。s:上面的源代码没有经过测试。

#2


47  

Works both locally and on live server without issues, and allows you to extend the delimited list of allowed file-extensions:

可以在本地和实时服务器上工作,没有问题,并允许您扩展允许文件扩展的分隔列表:

var folder = "images/";

$.ajax({
    url : folder,
    success: function (data) {
        $(data).find("a").attr("href", function (i, val) {
            if( val.match(/\.(jpe?g|png|gif)$/) ) { 
                $("body").append( "<img src='"+ folder + val +"'>" );
            } 
        });
    }
});

Basically an improvement on Roy's OA

基本上是对罗伊的OA的改进。

#3


9  

This is the way to add more file extentions, in the example given by Roy M J in the top of this page.

这是添加更多文件扩展的方法,在本页顶部Roy mj给出的示例中。

var fileextension = [".png", ".jpg"];
$(data).find("a:contains(" + (fileextension[0]) + "), a:contains(" + (fileextension[1]) + ")").each(function () { // here comes the rest of the function made by Roy M J   

In this example I have added more contains.

在本例中,我添加了更多的包含。

#4


5  

Here is one way to do it. Involves doing a little PHP as well.

这里有一个方法。还需要做一个小PHP。

The PHP part:

PHP部分:

$filenameArray = [];

$handle = opendir(dirname(realpath(__FILE__)).'/images/');
        while($file = readdir($handle)){
            if($file !== '.' && $file !== '..'){
                array_push($filenameArray, "images/$file");
            }
        }

echo json_encode($filenameArray);

The jQuery part:

jQuery的部分:

$.ajax({
            url: "getImages.php",
            dataType: "json",
            success: function (data) {

                $.each(data, function(i,filename) {
                    $('#imageDiv').prepend('<img src="'+ filename +'"><br>');
                });
            }
        });

So basically you do a PHP file to return you the list of image filenames as JSON, grab that JSON using an ajax call, and prepend/append them to the html. You would probably want to filter the files u grab from the folder.

所以基本上,你做一个PHP文件返回给你的图像文件名列表为JSON,使用ajax调用获取那个JSON,并将它们添加到html中。您可能想要从文件夹中过滤u抓取的文件。

Had some help on the php part from 1

对php部分有帮助吗

#5


2  

If, as in my case, you would like to load the images from a local folder on your own machine, then there is a simple way to do it with a very short Windows batch file. This uses the ability to send the output of any command to a file using > (to overwrite a file) and >> (to append to a file).

如果您想在自己的计算机上从本地文件夹中加载映像,那么有一种简单的方法可以使用非常短的Windows批处理文件来实现这一点。这使用了使用>(用于覆盖文件)和>>(用于附加到文件)将任何命令的输出发送到文件的能力。

Potentially, you could output a list of filenames to a plain text file like this:

可能,您可以将文件名列表输出到这样的纯文本文件:

dir /B > filenames.txt

However, reading in a text file requires more faffing around, so I output a javascript file instead, which can then be loaded in your to create a global variable with all the filenames in it.

但是,在文本文件中阅读需要更多的操作,所以我输出了一个javascript文件,然后在您的创建一个全局变量,并在其中包含所有的文件名。

echo var g_FOLDER_CONTENTS = mlString(function() { /*! > folder_contents.js
dir /B images >> folder_contents.js
echo */}); >> folder_contents.js

The reason for the weird function with comment inside notation is to get around the limitation on multi-line strings in Javascript. The output of the dir command cannot be formatted to write a correct string, so I found a workaround here.

之所以出现带有注释的奇怪函数,是因为它绕过了Javascript中多行字符串的限制。无法格式化dir命令的输出来编写正确的字符串,因此我在这里找到了一个解决方案。

function mlString(f) {
    return f.toString().
        replace(/^[^\/]+\/\*!?/, '').
        replace(/\*\/[^\/]+$/, '');
}

Add this in your main code before the generated javascript file is run, and then you will have a global variable called g_FOLDER_CONTENTS, which is a string containing the output from the dir command. This can then be tokenized and you'll have a list of filenames, with which you can do what you like.

在运行生成的javascript文件之前,在主代码中添加这个内容,然后您将有一个名为g_FOLDER_CONTENTS的全局变量,该变量是一个包含来自dir命令的输出的字符串。然后可以对它进行标记,您将得到一个文件名列表,您可以使用该列表来执行您喜欢的操作。

var filenames = g_FOLDER_CONTENTS.match(/\S+/g);

Here's an example of it all put together: image_loader.zip

这里有一个例子:image_loader.zip

In the example, run.bat generates the Javascript file and opens index.html, so you needn't open index.html yourself.

在这个例子中,运行。bat生成Javascript文件并打开索引。html,所以你不必打开索引。自己的html。

NOTE: .bat is an executable type in Windows, so open them in a text editor before running if you are downloading from some random internet link like this one.

注意:.bat是Windows中的可执行类型,所以在运行之前在文本编辑器中打开它们,如果您是从某个随机的internet链接下载的,比如这个。

If you are running Linux or OSX, you can probably do something similar to the batch file and produce a correctly formatted javascript string without any of the mlString faff.

如果您正在运行Linux或OSX,您可能可以做一些类似于批处理文件的事情,并生成一个没有任何mlString faff的格式正确的javascript字符串。

#6


1  

$(document).ready(function(){
var dir = "test/"; // folder location
var fileextension = ".jpg"; // image format
var i = "1";
$(function imageloop(){
 $("<img />").attr('src', dir + i + fileextension ).appendTo(".testing");
 if (i==13){
 alert('loaded');
 }
 else{
 i++;
 imageloop();
 };
       });   
});

for this script i have named my image files in folder as 1.jpg, 2.jpg, 3.jpg,.... to 13.jpg. You can change directory and file name as you wish.

这个脚本我叫jpg图像文件在文件夹中1.,2. jpg,3. jpg,....13. jpg。您可以随意更改目录和文件名。

#7


0  

You can't do this automatically. Your JS can't see the files in the same directory as it.

你不能自动这么做。您的JS无法看到与它相同的目录中的文件。

Easiest is probably to give a list of those image names to your JavaScript.

最简单的方法可能是向JavaScript提供这些图像名称的列表。

Otherwise, you might be able to fetch a directory listing from the web server using JS and parse it to get the list of images.

否则,您可能可以使用JS从web服务器获取目录列表并解析它以获取图像列表。

#8


0  

In jQuery you can use Ajax to call a server-side script. The server-side script will find all the files in the folder and return them to your html file where you will need to process the returned information.

在jQuery中,可以使用Ajax调用服务器端脚本。服务器端脚本将找到文件夹中的所有文件,并将它们返回到html文件中,您需要在该文件中处理返回的信息。

#9


0  

You can use the fs.readdir or fs.readdirSync methods to get the file names in the directory.

您可以使用fs。readdir或fs。readdirSync方法获取目录中的文件名。

The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.

这两种方法的不同之处在于,第一个方法是异步的,所以您必须提供一个回调函数,当读过程结束时,它将被执行。

The second is synchronous, it will returns the file name array, but it will stop any further execution of your code until the read process ends.

第二个是同步的,它将返回文件名数组,但是它将停止对代码的任何进一步执行,直到读取过程结束。

After that you simply have to iterate through the names and using append function, add them to their appropriate locations. To check out how it works see HTML DOM and JS reference

之后,您只需遍历名称并使用append函数,将它们添加到适当的位置。要查看它是如何工作的,请参阅HTML DOM和JS引用

#10


0  

Add the following script:

添加以下脚本:

<script type="text/javascript">

function mlString(f) {
    return f.toString().
        replace(/^[^\/]+\/\*!?/, '');
        replace(/\*\/[^\/]+$/, '');
}

function run_onload() {
    console.log("Sample text for console");
    var filenames = g_FOLDER_CONTENTS.match(/\S+/g);
    var fragment = document.createDocumentFragment();
    for (var i = 0; i < filenames.length; ++i) {
        var extension = filenames[i].substring(filenames[i].length-3);
        if (extension == "png" || extension == "jpg") {

var iDiv = document.createElement('div');
iDiv.id = 'images';
iDiv.className = 'item';
document.getElementById("image_div").appendChild(iDiv);
iDiv.appendChild(fragment);

            var image = document.createElement("img");
            image.className = "fancybox";
            image.src = "images/" + filenames[i];
            fragment.appendChild(image);
        }
    }
     document.getElementById("images").appendChild(fragment);

}

</script>

then create a js file with the following:

然后创建一个js文件,如下所示:

var g_FOLDER_CONTENTS = mlString(function() { /*! 
1.png
2.png
3.png 
*/}); 

#11


0  

Using Chrome, searching for the images files in links (as proposed previously) didn't work as it is generating something like:

使用Chrome,搜索链接中的图像文件(如前所述)并不奏效,因为它生成的内容如下:

(...) i18nTemplate.process(document, loadTimeData);
</script>
<script>start("current directory...")</script>
<script>addRow("..","..",1,"170 B","10/2/15, 8:32:45 PM");</script>
<script>addRow("fotos-interessantes-11.jpg","fotos-interessantes-> 11.jpg",false,"","");</script>

Maybe the most reliable way is to do something like this:

也许最可靠的方法是这样做:

var folder = "img/";

$.ajax({
    url : folder,
    success: function (data) {
        var patt1 = /"([^"]*\.(jpe?g|png|gif))"/gi;     // extract "*.jpeg" or "*.jpg" or "*.png" or "*.gif"
        var result = data.match(patt1);
        result = result.map(function(el) { return el.replace(/"/g, ""); });     // remove double quotes (") surrounding filename+extension // TODO: do this at regex!

        var uniqueNames = [];                               // this array will help to remove duplicate images
        $.each(result, function(i, el){
            var el_url_encoded = encodeURIComponent(el);    // avoid images with same name but converted to URL encoded
            console.log("under analysis: " + el);
            if($.inArray(el, uniqueNames) === -1  &&  $.inArray(el_url_encoded, uniqueNames) === -1){
                console.log("adding " + el_url_encoded);
                uniqueNames.push(el_url_encoded);
                $("#slider").append( "<img src='" + el_url_encoded +"' alt=''>" );      // finaly add to HTML
            } else{   console.log(el_url_encoded + " already in!"); }
        });
    },
    error: function(xhr, textStatus, err) {
       alert('Error: here we go...');
       alert(textStatus);
       alert(err);
       alert("readyState: "+xhr.readyState+"\n xhrStatus: "+xhr.status);
       alert("responseText: "+xhr.responseText);
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

#12


0  

Listar una serie de imágenes contenidas en una carpeta y mostrarlas en el body

this is the code that works for me, what I want is to list the images directly on my page so that you just have to put the directory where you can find the images for example -> dir = "images /" I do a substring var pathName = filename.substring (filename.lastIndexOf ('/') + 1); with which I make sure to just bring the name of the files listed and at the end I link my URL to publish it in the body   $ ("body"). append ($ (" "));

这是对我有用的代码,我想要的是直接在我的页面上列出图像,这样你只需要把目录放在你可以找到图像的地方,例如-> dir = "images /"我做了一个var pathName = filename子字符串。substring(文件名。lastIndexOf(“/”)+ 1);我确保只带列出的文件的名称,并在最后链接我的URL以在body $(“body”)中发布它。追加($(" "));

Para correrlo necesitan la librería de jquery
Espero les sea útil Saludos desde México.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="jquery-1.6.3.min.js"></script>
        <script>


        var dir = "imagenes/";
        var fileextension = ".jpg";
        $.ajax({
            //This will retrieve the contents of the folder if the folder is configured as 'browsable'
            url: dir,
            success: function (data) {
                //Lsit all png file names in the page
                $(data).find("a:contains(" + fileextension + ")").each(function () {
                    var filename = this.href.replace(window.location.pathname, "").replace("http://", "");
            var pathName = filename.substring(filename.lastIndexOf('/') + 1);               
                    $("body").append($("<img src=" + dir + pathName + "></img>"));
            console.log(dir+pathName);
                });
            }
        });



        </script>

  </head>
  <body>
<img src="1_1.jpg">
  </body>
</html>

#1


49  

Use :

使用:

var dir = "Src/themes/base/images/";
var fileextension = ".png";
$.ajax({
    //This will retrieve the contents of the folder if the folder is configured as 'browsable'
    url: dir,
    success: function (data) {
        //List all .png file names in the page
        $(data).find("a:contains(" + fileextension + ")").each(function () {
            var filename = this.href.replace(window.location.host, "").replace("http://", "");
            $("body").append("<img src='" + dir + filename + "'>");
        });
    }
});

If you have other extensions, you can make it an array and then go through that one by one using in_array().

如果有其他扩展,可以将其设置为数组,然后使用in_array()逐个遍历该扩展。

P.s : The above source code is not tested.

P。s:上面的源代码没有经过测试。

#2


47  

Works both locally and on live server without issues, and allows you to extend the delimited list of allowed file-extensions:

可以在本地和实时服务器上工作,没有问题,并允许您扩展允许文件扩展的分隔列表:

var folder = "images/";

$.ajax({
    url : folder,
    success: function (data) {
        $(data).find("a").attr("href", function (i, val) {
            if( val.match(/\.(jpe?g|png|gif)$/) ) { 
                $("body").append( "<img src='"+ folder + val +"'>" );
            } 
        });
    }
});

Basically an improvement on Roy's OA

基本上是对罗伊的OA的改进。

#3


9  

This is the way to add more file extentions, in the example given by Roy M J in the top of this page.

这是添加更多文件扩展的方法,在本页顶部Roy mj给出的示例中。

var fileextension = [".png", ".jpg"];
$(data).find("a:contains(" + (fileextension[0]) + "), a:contains(" + (fileextension[1]) + ")").each(function () { // here comes the rest of the function made by Roy M J   

In this example I have added more contains.

在本例中,我添加了更多的包含。

#4


5  

Here is one way to do it. Involves doing a little PHP as well.

这里有一个方法。还需要做一个小PHP。

The PHP part:

PHP部分:

$filenameArray = [];

$handle = opendir(dirname(realpath(__FILE__)).'/images/');
        while($file = readdir($handle)){
            if($file !== '.' && $file !== '..'){
                array_push($filenameArray, "images/$file");
            }
        }

echo json_encode($filenameArray);

The jQuery part:

jQuery的部分:

$.ajax({
            url: "getImages.php",
            dataType: "json",
            success: function (data) {

                $.each(data, function(i,filename) {
                    $('#imageDiv').prepend('<img src="'+ filename +'"><br>');
                });
            }
        });

So basically you do a PHP file to return you the list of image filenames as JSON, grab that JSON using an ajax call, and prepend/append them to the html. You would probably want to filter the files u grab from the folder.

所以基本上,你做一个PHP文件返回给你的图像文件名列表为JSON,使用ajax调用获取那个JSON,并将它们添加到html中。您可能想要从文件夹中过滤u抓取的文件。

Had some help on the php part from 1

对php部分有帮助吗

#5


2  

If, as in my case, you would like to load the images from a local folder on your own machine, then there is a simple way to do it with a very short Windows batch file. This uses the ability to send the output of any command to a file using > (to overwrite a file) and >> (to append to a file).

如果您想在自己的计算机上从本地文件夹中加载映像,那么有一种简单的方法可以使用非常短的Windows批处理文件来实现这一点。这使用了使用>(用于覆盖文件)和>>(用于附加到文件)将任何命令的输出发送到文件的能力。

Potentially, you could output a list of filenames to a plain text file like this:

可能,您可以将文件名列表输出到这样的纯文本文件:

dir /B > filenames.txt

However, reading in a text file requires more faffing around, so I output a javascript file instead, which can then be loaded in your to create a global variable with all the filenames in it.

但是,在文本文件中阅读需要更多的操作,所以我输出了一个javascript文件,然后在您的创建一个全局变量,并在其中包含所有的文件名。

echo var g_FOLDER_CONTENTS = mlString(function() { /*! > folder_contents.js
dir /B images >> folder_contents.js
echo */}); >> folder_contents.js

The reason for the weird function with comment inside notation is to get around the limitation on multi-line strings in Javascript. The output of the dir command cannot be formatted to write a correct string, so I found a workaround here.

之所以出现带有注释的奇怪函数,是因为它绕过了Javascript中多行字符串的限制。无法格式化dir命令的输出来编写正确的字符串,因此我在这里找到了一个解决方案。

function mlString(f) {
    return f.toString().
        replace(/^[^\/]+\/\*!?/, '').
        replace(/\*\/[^\/]+$/, '');
}

Add this in your main code before the generated javascript file is run, and then you will have a global variable called g_FOLDER_CONTENTS, which is a string containing the output from the dir command. This can then be tokenized and you'll have a list of filenames, with which you can do what you like.

在运行生成的javascript文件之前,在主代码中添加这个内容,然后您将有一个名为g_FOLDER_CONTENTS的全局变量,该变量是一个包含来自dir命令的输出的字符串。然后可以对它进行标记,您将得到一个文件名列表,您可以使用该列表来执行您喜欢的操作。

var filenames = g_FOLDER_CONTENTS.match(/\S+/g);

Here's an example of it all put together: image_loader.zip

这里有一个例子:image_loader.zip

In the example, run.bat generates the Javascript file and opens index.html, so you needn't open index.html yourself.

在这个例子中,运行。bat生成Javascript文件并打开索引。html,所以你不必打开索引。自己的html。

NOTE: .bat is an executable type in Windows, so open them in a text editor before running if you are downloading from some random internet link like this one.

注意:.bat是Windows中的可执行类型,所以在运行之前在文本编辑器中打开它们,如果您是从某个随机的internet链接下载的,比如这个。

If you are running Linux or OSX, you can probably do something similar to the batch file and produce a correctly formatted javascript string without any of the mlString faff.

如果您正在运行Linux或OSX,您可能可以做一些类似于批处理文件的事情,并生成一个没有任何mlString faff的格式正确的javascript字符串。

#6


1  

$(document).ready(function(){
var dir = "test/"; // folder location
var fileextension = ".jpg"; // image format
var i = "1";
$(function imageloop(){
 $("<img />").attr('src', dir + i + fileextension ).appendTo(".testing");
 if (i==13){
 alert('loaded');
 }
 else{
 i++;
 imageloop();
 };
       });   
});

for this script i have named my image files in folder as 1.jpg, 2.jpg, 3.jpg,.... to 13.jpg. You can change directory and file name as you wish.

这个脚本我叫jpg图像文件在文件夹中1.,2. jpg,3. jpg,....13. jpg。您可以随意更改目录和文件名。

#7


0  

You can't do this automatically. Your JS can't see the files in the same directory as it.

你不能自动这么做。您的JS无法看到与它相同的目录中的文件。

Easiest is probably to give a list of those image names to your JavaScript.

最简单的方法可能是向JavaScript提供这些图像名称的列表。

Otherwise, you might be able to fetch a directory listing from the web server using JS and parse it to get the list of images.

否则,您可能可以使用JS从web服务器获取目录列表并解析它以获取图像列表。

#8


0  

In jQuery you can use Ajax to call a server-side script. The server-side script will find all the files in the folder and return them to your html file where you will need to process the returned information.

在jQuery中,可以使用Ajax调用服务器端脚本。服务器端脚本将找到文件夹中的所有文件,并将它们返回到html文件中,您需要在该文件中处理返回的信息。

#9


0  

You can use the fs.readdir or fs.readdirSync methods to get the file names in the directory.

您可以使用fs。readdir或fs。readdirSync方法获取目录中的文件名。

The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.

这两种方法的不同之处在于,第一个方法是异步的,所以您必须提供一个回调函数,当读过程结束时,它将被执行。

The second is synchronous, it will returns the file name array, but it will stop any further execution of your code until the read process ends.

第二个是同步的,它将返回文件名数组,但是它将停止对代码的任何进一步执行,直到读取过程结束。

After that you simply have to iterate through the names and using append function, add them to their appropriate locations. To check out how it works see HTML DOM and JS reference

之后,您只需遍历名称并使用append函数,将它们添加到适当的位置。要查看它是如何工作的,请参阅HTML DOM和JS引用

#10


0  

Add the following script:

添加以下脚本:

<script type="text/javascript">

function mlString(f) {
    return f.toString().
        replace(/^[^\/]+\/\*!?/, '');
        replace(/\*\/[^\/]+$/, '');
}

function run_onload() {
    console.log("Sample text for console");
    var filenames = g_FOLDER_CONTENTS.match(/\S+/g);
    var fragment = document.createDocumentFragment();
    for (var i = 0; i < filenames.length; ++i) {
        var extension = filenames[i].substring(filenames[i].length-3);
        if (extension == "png" || extension == "jpg") {

var iDiv = document.createElement('div');
iDiv.id = 'images';
iDiv.className = 'item';
document.getElementById("image_div").appendChild(iDiv);
iDiv.appendChild(fragment);

            var image = document.createElement("img");
            image.className = "fancybox";
            image.src = "images/" + filenames[i];
            fragment.appendChild(image);
        }
    }
     document.getElementById("images").appendChild(fragment);

}

</script>

then create a js file with the following:

然后创建一个js文件,如下所示:

var g_FOLDER_CONTENTS = mlString(function() { /*! 
1.png
2.png
3.png 
*/}); 

#11


0  

Using Chrome, searching for the images files in links (as proposed previously) didn't work as it is generating something like:

使用Chrome,搜索链接中的图像文件(如前所述)并不奏效,因为它生成的内容如下:

(...) i18nTemplate.process(document, loadTimeData);
</script>
<script>start("current directory...")</script>
<script>addRow("..","..",1,"170 B","10/2/15, 8:32:45 PM");</script>
<script>addRow("fotos-interessantes-11.jpg","fotos-interessantes-> 11.jpg",false,"","");</script>

Maybe the most reliable way is to do something like this:

也许最可靠的方法是这样做:

var folder = "img/";

$.ajax({
    url : folder,
    success: function (data) {
        var patt1 = /"([^"]*\.(jpe?g|png|gif))"/gi;     // extract "*.jpeg" or "*.jpg" or "*.png" or "*.gif"
        var result = data.match(patt1);
        result = result.map(function(el) { return el.replace(/"/g, ""); });     // remove double quotes (") surrounding filename+extension // TODO: do this at regex!

        var uniqueNames = [];                               // this array will help to remove duplicate images
        $.each(result, function(i, el){
            var el_url_encoded = encodeURIComponent(el);    // avoid images with same name but converted to URL encoded
            console.log("under analysis: " + el);
            if($.inArray(el, uniqueNames) === -1  &&  $.inArray(el_url_encoded, uniqueNames) === -1){
                console.log("adding " + el_url_encoded);
                uniqueNames.push(el_url_encoded);
                $("#slider").append( "<img src='" + el_url_encoded +"' alt=''>" );      // finaly add to HTML
            } else{   console.log(el_url_encoded + " already in!"); }
        });
    },
    error: function(xhr, textStatus, err) {
       alert('Error: here we go...');
       alert(textStatus);
       alert(err);
       alert("readyState: "+xhr.readyState+"\n xhrStatus: "+xhr.status);
       alert("responseText: "+xhr.responseText);
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

#12


0  

Listar una serie de imágenes contenidas en una carpeta y mostrarlas en el body

this is the code that works for me, what I want is to list the images directly on my page so that you just have to put the directory where you can find the images for example -> dir = "images /" I do a substring var pathName = filename.substring (filename.lastIndexOf ('/') + 1); with which I make sure to just bring the name of the files listed and at the end I link my URL to publish it in the body   $ ("body"). append ($ (" "));

这是对我有用的代码,我想要的是直接在我的页面上列出图像,这样你只需要把目录放在你可以找到图像的地方,例如-> dir = "images /"我做了一个var pathName = filename子字符串。substring(文件名。lastIndexOf(“/”)+ 1);我确保只带列出的文件的名称,并在最后链接我的URL以在body $(“body”)中发布它。追加($(" "));

Para correrlo necesitan la librería de jquery
Espero les sea útil Saludos desde México.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="jquery-1.6.3.min.js"></script>
        <script>


        var dir = "imagenes/";
        var fileextension = ".jpg";
        $.ajax({
            //This will retrieve the contents of the folder if the folder is configured as 'browsable'
            url: dir,
            success: function (data) {
                //Lsit all png file names in the page
                $(data).find("a:contains(" + fileextension + ")").each(function () {
                    var filename = this.href.replace(window.location.pathname, "").replace("http://", "");
            var pathName = filename.substring(filename.lastIndexOf('/') + 1);               
                    $("body").append($("<img src=" + dir + pathName + "></img>"));
            console.log(dir+pathName);
                });
            }
        });



        </script>

  </head>
  <body>
<img src="1_1.jpg">
  </body>
</html>