简体   繁体   中英

How do I use AJAX to create a list of a server-side directory?

Given how most questions I've seen regarding this concept aren't clear with their end goal, I want to start off with a bit of Python code and use that as the base of this question.

from glob import glob

print(glob('*'))

The preceding code prints off a list of all files and/or folders it detects in a directory ( * marking the current directory that the script is running in), with the help of the glob module . So if I were to run the script within a directory with a folder and two images, the resulting output would be the following list:

['folder1','image1.png','image2.png','script.py']

What I'm looking to do is to recreate this functionality within Javascript for content local to a webserver. (To make life easy, let's say this is all running off localhost ) From what I've managed to find, AJAX is the best modern method of Javascript file handling there is. With it, I've been able to call an httpsRequest to the folder I want, but the only response I've managed to get is an HTML dump of what I presume to be the server's file explorer. Trying to use modifiers such as responseText yield <empty sting> responses in the console. For context, this is the code I've currently been working with:

function() {
    httpRequest = new XMLHttpRequest();

    if (!httpRequest) {
        alert("Giving up :( Cannot create an XMLHTTP instance");
        return false;
    }
    httpRequest.onreadystatechange = console.log(httpRequest);
    httpRequest.open('GET', '/testing/');
    httpRequest.send();
}

Gotta love the XY problem .

Why this doesn't work

AJAX's functionality is not designed for dynamic file handling like Python's glob . It's primarily designed to exchange information one file at a time, with the ability to alter that file in the XMLHttpRequest . This isn't a downside, as it's useful for handing config files in JSON or communicating with a PHP database. It's also worth bringing up something mentioned in Tangentially Perpendicular's comment:

You'll only get a directory listing if the web server is set up to provide one, and not always then. [That said] you probably don't want to do that for security reasons.

"Then how do I create a dynamic list of articles to show up in my HTML?"

And there's our X.

What you really want is a Static Site Generator . With it, you'll be able to create and compile a site that handles creating that article list for you.

For those looking for further reading, keep in mind that SSG's are often used in reference to the Jamstack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM