Ajax query to display multiple content

Asked

Viewed 220 times

1

At the moment I have some banners that are loaded via ajax, and each one makes a request to load the html. Now I’m trying to optimize these processes and decided to make a single request to load as many banners are available on the page.

Basically I have a div with the banner size, and by javascript I loop in search of these elements and pass as argument by ajax to make the request.

var tamanho = new Array
$('.banners').each(function( i )
{
    tamanho[ i ] = $(this).attr('tamanho')
})

$.ajax({ ... })

So far it works. I step the sizes and get the result with a json guy: {"json":{"tamanhoA":["banner"],"tamanhoB":["banner","banner"]}}. In this example the size is a single banner and size are 2 banners.

The problem is the time to display the banners in the right places. For this I need to repeat the loop equal to the top to catch the Divs and one more loop in the result to get the position in the array.


I was wondering if there is a simpler solution for this case without having to repeat all these loops? This json it was the simplest I could find to make it work, but I can adapt the result to ideas.

1 answer

1


What occurs to me to avoid 2 loops in the DOM is to create an object with the element right in the first loop. I also changed the .each() for .map() because I prefer it this way.

Something like:

var tamanho = $('.banners').map(function(i){
    return {
        tamanho: $(this).attr('tamanho'),
        elemento: this
    }
}).get();

$.ajax({ ... 
    complete: function(conteudos){
        $(conteudos).each(function(i){ tamanho[i].elemento.innerHTML = this;});
    }
});

Another option, same as yours but keeping the elements in the first one (and only) .each() of GIFT:

var tamanhos = [], elementos = [];
$('.banners').each(function(i){
        tamanhos[i] = $(this).attr('tamanho')
        elementos[i] = this
});

$.ajax({ ... 
    complete: function(conteudos){
        $(conteudos).each(function(i){ tamanho[i].elemento.innerHTML = this;});
    }
});
  • It seems to be the right path, but there is one that should be easy to solve. I need to run the sizes of the banners that were found through the ajax as an argument. In the code I posted, I’ll be docking an array and making a Count with php to see how many banners each will be returned. How to adapt in this model?

  • @Papacharlie in this case has to be similar to the idea you already had... I edited a little in a hurry but I’ll take a look again later.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.