How to read directory using jQuery .ajax()?

CW Holeman II picture CW Holeman II · Mar 25, 2010 · Viewed 9.5k times · Source

Using jQuery .ajax() to read "./ex.html" returns the expected contents of the file in the first alert box. Using the same call just changing the request to "./" does not return an expected directory listing in the second alert box.

<html>
<head>
</head>
<body>
<script type="text/JavaScript" src="jquery.js"></script>
<script type="text/JavaScript">
    alert($.ajax({type: "GET", url: 'ex.html', async: false}).responseText);
    alert($.ajax({type: "GET", url: '.',       async: false}).responseText);
</script>
</body>
</html>

When access the file directly: $ firefox ex.html the results are as described. $ firefox . displays:

Index of file:///home/cwhii/work/jq/ex

Up to higher level directory

Name Size Last Modified

ex.html 1 KB 03/24/2010 10:29:37 PM

jquery.js 161 KB 03/17/2010 05:16:58 PM

Then clicking on the ex.html link produces the expected file content in the first alert box and the directory listing in the second alert box.

In summary, invoking firefox with the file name on the command line does not produce the directory listing but when navigating to the same file via the link on the directory page the second alert box does display the listing.

Additionally, I invoked Google Chrome browser 5.0.307.11 beta in all the above described ways and all of the results produced no directory listings in the alert boxes even though $ google-chrome . produces a directory listing page.

Answer

Ben Rowe picture Ben Rowe · Mar 25, 2010

You're going to need some sort of server side code to generate a list of files/folders within a directory. Your web server is most likely redirecting that request to either the default page for the directory (index.html, default.html, etc), or it throwing a 404/403/etc page, since the page you've requested doesn't exist.