简体   繁体   中英

How can I load multiple html files from a folder into a div

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);
}

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); }); }); 

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

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