简体   繁体   中英

How to do multiple Ajax calls when page is first loaded while using the same HTML divs

I currently have my HTML site set up where I pass a div id as data into my Ajax.

<div id="1" class="stats">
    DATA GOES IN HERE
</div>
<div id="2" class="stats">
    DATA GOES IN HERE
</div>

I have it so that when the page first loads, an Ajax call is loaded that finds the div id and makes use of it back-end to bring the DATA forward.

$(document).ready(function(){
var fId = $(".stats").attr("id");
$.ajax({
    url: 'get_stats',
    type: 'GET',
    data: {fId : fId},
    success: function(data) {
        $("#"+fId).html(data);
    },
    error: function(data){
        alert("ERROR: " + data);
    }
});
});

The data can be brought. However, I have about 26 of these divs and I need to do this call 26 times. The problem is, the call is only made once and the data is only loaded for the very first div.

How can I make it so that I pass the data from all 26 divs into the Ajax call and bring it into the HTML when the page is first loaded?

You can just do that with a loop like:

let divs = $(".stats");

$.each(divs, function (div) {
     //..do your ajax request here
});

Please try this

 $(document).ready(function(){ $(".stats").each((i,e)=>{ let fId=$(e).attr("id"); $.ajax({ url: 'get_stats', type: 'GET', data: {fId : fId}, success: function(data) { $("#"+fId).html(data); }, error: function(data){ alert("ERROR: " + data); } }); }) });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="1" class="stats"> DATA GOES IN HERE </div> <div id="2" class="stats"> DATA GOES IN HERE </div>

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