简体   繁体   中英

How can I use JQuery to populate multiple divs with content from external html page and update that content based on attributes on each div?

I have two divs on a page that need be populated with the same block of code from an external html page. I am calling a separate api per div that should dynamically replace each variable in the external content block.

I am using .load() to get the external content, but how can i pass the api url parameter for each div since onload() only works on specific tags?

html:

<div onload="getCard('api_url',this.id)" id="api_div_1">Here</div>

<div onload="getCard('api_url2',this.id)" id="api_div_2">Here</div>

jquery:

function getCard(api_url, div_id) {
    $.ajax({
        url: api_url,
        dataType: 'json',
        async: false,
        success: function(result) {
            var cards = result;
            var card = cards['cards'][0];
            $("#" + div_id).load("https://external.html div.schumer-container");
        },
        error: function() {
            alert('error');
        }
    });
}

I guess you mean something like this: Simply store the api source as an attribute on the html element. Then you can loop over every element with javascript to call the api to populate it.

 $(document).ready(function(){ $( "div" ).each(function( index ) { var apisrc = $(this).attr("data-apisrc"), $this = $(this); $.ajax({ url: apisrc, dataType: 'json', async: false, success: function(result) { $this.text(result); error: function() { $this.text("content could not be loaded"); //alert('error'); } }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="api_div_1" data-apisrc="https://source1">Here</div> <div id="api_div_2" data-apisrc="https://source2">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