Can one jQuery call load multiple HTML containers?
I was wondering if there's a way to allow jQu开发者_JAVA技巧ery loading multiple HTML containers with just one call. For example:
.
<div id='one'></div>
<div id='two'></div>
.
.
<script type="text/javascript">
jQuery("#one").load("somephpmodule.php", "",
function(responseText, textStatus, XMLHttpRequest) {
if(textStatus == 'error') {
jQuery('#one').html('There was an error making the AJAX request');
}});
</script>
.
In the code above, only div
"one" will be loaded from the somephpmodule.php
output. How to load also div
"two" with one call? Or simply do I need to issue multiple calls?
I'd do it like this:
loadUserModules.php handles all of the users modules and returns an array where keys are div IDs (one, two, three etc) and values are the HTML blocks you'll be adding to the page.
This will make one big call to load all your modules.
<script type="text/javascript">
$.getJSON('loadUserModuels.php', function(data) {
$.each(data, function(index, value) {
$("#" + index).html(value);
});
});
</script>
Place both s in one new empty or another tag of your choice with id and load to it.
Personally, I would use the jquery.ajax function to return json with both bits of information, then at clientside, I would get the script to place the appropriate data from the json in to appropriate div tags.
Using this method, you could have many div tags, and a single request would return all the data in json form, which could easily be placed appropriately at clientside.
You don't need to issue multiple calls, you just need to format your request and response differently.
Example, useing json.
$.ajax( {
url: url,
dataType: 'json',
data: data,
success: function( response ) {
$("#one").html( response.one );
$("#two").html( response.two );
}
} );
function loadModules() {
$('#section div[class="module"]').each(function() {
var ajaxModule = $(this);
$.ajax({
url: 'modules/' + $(ajaxModule).attr('modulePage'),
cache: false,
type: 'post',
async:true,
success: function(data){
if(data)
$(ajaxModule).html(data);
else
$(ajaxModule).html('The page that you requested was not found.');
}
});
});
}
You can use a function like this. I wrote it for load modules via ajax. You can set your modules like this;
<div class="module" modulePage="MODULETEST.PHP"></div>
And call this function on;
$(document).ready(function() {...});
It will gonna load all modules.
Btw, don't forget async:true statement on ajax. If not, when you load 3 or more modules at the same time, your page gonna freeze. Normally async:true statement is default setted but if you assigned async:false on ajaxSetup function like me, you don't have to forget it.
good luck!
精彩评论