0

Say I've got folder "../cars/" that holds multiple html files, and I want to load all of these files into another html file.

I could easily go about this by doing something like:

$(document).ready(function (){
     $("#all_cars").load("../cars/civic.html");
     $("#all_cars").load("../cars/durango.html");
     $("#all_cars").load("../cars/mustang.html");
     $("#all_cars").load("../cars/r8.html");
     ... and so on
});

But I'd like to do this in a more sophisticated manner. I also don't want to have to code the file names into my js file. I'd rather be able to remove the file from the folder and now have it load anymore. Is there a way I could get all the filenames in the cars folder and loop over them to load?

Kind of like this:

foreach(cfn in carsFilesNames){
     $("#all_cars").load("../cars/" + carsFileNames);
}
st0ve
  • 519
  • 3
  • 18

2 Answers2

1

Hopefully this is what you want:

$.each([
    'civic.html',
    'durango.html',
    'mustang.html',
    'r8.html'
], function(i,a){
    $("#all_cars").load("../cars/" + a);
});

$.each will go over the array.


If you wish to automatically get all files in the directory and list them, and you have PHP on your web server, add a file called carindex.php, set it's content to:
<?php

print json_encode(scandir('PATH/TO/cars/', 1));

?>

Then on the client side:

$.get('/carindex.php', function (a) {
    a.forEach(function (b) {
        $("#all_cars").load("../cars/" + b);
    });
});
Downgoat
  • 13,771
  • 5
  • 46
  • 69
  • This would work, but would require me to know the names of the files ahead of time. – st0ve Apr 26 '15 at 01:39
  • @stewartm I added another version but in order to automatically transverse the directory, you need PHP or another server-side language – Downgoat Apr 26 '15 at 01:40
0

You can try with this:

jQuery.ajaxSetup({ async: false }); //if order matters
$.get("file.htm", '', function (data) { $("#result").append(data); });
$.get("pippo.htm", '', function (data) { $("#result").append(data); });
jQuery.ajaxSetup({ async: true });  //if order matters
Stefan Đorđević
  • 1,781
  • 3
  • 15
  • 14