7

How do i load multiple html files and putting them into a specified html element?

I tried with no changes:

$('#asd').load('file.html,pippo.html');
John Munsch
  • 19,530
  • 8
  • 42
  • 72
itsme
  • 48,972
  • 96
  • 224
  • 345

2 Answers2

9

you could get multiple items and add them to the element.

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
earth_tom
  • 831
  • 1
  • 5
  • 13
  • 1
    `data1` and `data2` are deferred objects, not text/html. Your code as posted will append the string `[object Object][object Object]` to `.result` – Kevin B May 15 '12 at 17:45
  • You're right @Kevin B. I've modified the post to include the callback functions in the get() calls. – earth_tom May 15 '12 at 19:46
  • 1
    I hate to rain on this parade, but if getting wwa.htm takes way longer than getting wb0tpl.htm then you could easily have them append out of order (or if they take similar time, in varying order each time you try it). Kevin B's solution does not have that problem. – John Munsch May 15 '12 at 19:55
  • Yeah to let this code work any time, you should do the second $.get in the callback of the first $.get. Which becomes quite messy with lots of $.get's – Anonymous May 15 '12 at 20:05
  • I don't get why u made a function appendToResult(). Why didn't u just use $("#result").append(); ? – Anonymous May 15 '12 at 20:07
  • 1
    @gl3nn, I changed to include the append call. Also, I added the wrapping with "async" in case order matters. – earth_tom May 15 '12 at 20:17
  • great! I like your async : false method. Wouldn't have thought of that. – Anonymous May 15 '12 at 20:19
  • 2
    @gl3nn Using `async:false` locks the browser during the requests and results in the requests being sent out sequentially rather simultaneously, possibly causing it to take longer to get all of the requested html (causing the previously mentioned lock to last longer). – Kevin B May 15 '12 at 20:48
  • Nobody should be using synchronous HTTP requests in 2021. – Pointy Feb 01 '21 at 13:29
7

Try this, using deferred objects.

var defArr = [];
defArr.push($.get('file.html'));
defArr.push($.get('pippo.html'));
$.when.apply($,defArr).done(function(response1,response2){
    $('.result').html(response1[2].responseText + response2[2].responseText);
});
Kevin B
  • 94,570
  • 16
  • 163
  • 180