How do I count files in a directory using jQuery?

前端 未结 4 1688
[愿得一人]
[愿得一人] 2020-12-06 16:06

I\'d like to count the number of files in a folder and return that number to set a variable in a .js file.

Essentially, I have X number of images in a folder. When t

相关标签:
4条回答
  • 2020-12-06 16:14

    Simple way:

    <?php
        $dir = "images";
        $file_count = count(glob("{$dir}/*.*"));
    ?>
    <html>
    <head>
    <title>Welcome</title>
    </head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){ 
    
        var dir = <?php echo $dir ?>;
        var file_count = <?php echo $file_count ?>;
    
        $('#msg').html('File count in folder ' + dir + ' is ' + file_count);
    });
    </script>
    <body>
    <div id="msg"></div>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-12-06 16:21

    I would do it like this

    echo count(glob("{$_GET['dir']}/*.*"));
    
    0 讨论(0)
  • 2020-12-06 16:22

    This is the kind of task PHP is better suited for, keep your Javascript to the client-side. Write a very simple PHP script that counts the files in a folder

    echo iterator_count(new DirectoryIterator('/home/path/dir'));
    

    And call it from your JQuery script.

    $.get('numberoffiles.php', function(data) {
      alert(data);
    });
    
    0 讨论(0)
  • 2020-12-06 16:37

    If you must use client side and the files are numbered, preload the file and set the number when you get an error

    ...
    Img = new Image();
    Img.onerror=function() {
      maxImages=cnt-1;
    }
    Img.src = "image_"+cnt+".jpg";
    
    0 讨论(0)
提交回复
热议问题