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

2 Answers 2

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
9
  • 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
    Commented May 15, 2012 at 17:45
  • You're right @Kevin B. I've modified the post to include the callback functions in the get() calls.
    – earth_tom
    Commented May 15, 2012 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. Commented May 15, 2012 at 19:55
  • 1
    @gl3nn, I changed to include the append call. Also, I added the wrapping with "async" in case order matters.
    – earth_tom
    Commented May 15, 2012 at 20:17
  • 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
    Commented May 15, 2012 at 20:48
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);
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.