Javascript - Retrieve names of files in a folder

时间秒杀一切 提交于 2019-11-30 07:11:48
<html>
<body>
    <div id='fileNames'></div>
</body>
<script src="js/jquery.js"></script>

<script type="text/javascript">
    $(document).ready(function () 
    {
        $.get(".", function(data) 
        {
            $("#fileNames").append(data);
        });
    })
</script>

this will print all the files in a folder on webpage.

It looks like you are running it by double clicking on html file. So it will run in browser with file protocol. You have to run it from server like http://localhost/myhtml.html.

I have tried code in my system, it's working with server.

Plus

you have syntax error in below line

$(data).find('a:contains(" + fileExt + ")').each(function () {

replace above with this

$(data).find("a:contains(" + fileExt + ")").each(function () {

I'm on ubuntu system, and with chrome browser, you do not need to replace location. because it is returning relative path to location.

UPDATE

Your final code should look like this

<script type="text/javascript">//<![CDATA[
$(window).load(function(){
   var fileExt = ".xml";

        $(document).ready(function(){

            $.ajax({
                //This will retrieve the contents of the folder if the folder is configured as 'browsable'
                url: 'xml/',
                success: function (data) {
                    console.log(data);
                   $("#fileNames").html('<ul>');
                   //List all xml file names in the page

                    //var filename = this.href.replace(window.location, "").replace("http:///", "");
                   //$("#fileNames").append( '<li>'+filename+'</li>');

                    $(data).find("a:contains(" + fileExt + ")").each(function () {
                        $("#fileNames").append( '<li>'+$(this).text()+'</li>');
                    });
                    $("#fileNames").append('</ul>');
                }
            });

        });
});
//]]>
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!