简体   繁体   中英

Load items with ajax in div's

I'm currently using the following javascript to load items in aa few div's:

<script>
    $.ajax({
        url: 'load.php?type=divA',
        cache: false,     
        success: function(data){
        $('#divA').html(data); 
        }
    });   
    $.ajax({
        url: 'load.php?type=divB',
        cache: false,     
        success: function(data){
        $('#divB').html(data); 
        }
    });  </script>

HTML:

<div id="divA">
<!-- Load divA item here -->
</div>
<div id="divB">
<!-- Load divB item here -->
</div>

I'm looking (and think) there's a better way to do this. Similar to this: 1 function for a div's, which automatically loads the items in (multiply) div's:

function loadItem(<DIV ID>) {
 $.ajax({
            url: 'load.php?type=<DIV ID>',
            cache: false,     
            success: function(data){
            $('<DIV ID>').html(data); 
            }
        }); 
};

It can be done like this:

function loadItem(divId) {
    $.ajax({
        url: 'load.php?type=' + divId,
        cache: false,
        success: function (data) {
            $('#' + divId).html(data);
        }
    });
};

I think this is better:

function loadItem(div) {
   $.ajax({
      url: 'load.php?type='+div,
      cache: false,     
      success: function(data){
         $('#'+div).html(data); 
      }
   }); 
};

$(function(){
   $('div[id^="div"]').each(function(){
      loadItem(this.id);
   });
});

What this code is doing:

  1. make a global function putting function outside of doc ready.
  2. In the doc ready block loop through the div whose id starts with div and pass that id to the function.
  3. So if there are two divs then there will be two ajax calls.

This is a late reply:

$('div[class*="div"]').each(function(){ // class contains div
   loadItem(this.className.split(' ')[1]); 
});// split by ' ' space and pass the second index as arrays are 0 based index.

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