Ajax query to display multiple content

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 am trying to optimize these processes and I have decided to make a single request to load as many banners as are available on the page.

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

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

$.ajax({ ... })
So far it works. I pass the sizes and get the result with a json type: {"json":{"tamanhoA":["banner"],"tamanhoB":["banner","banner"]}} . In this example sizeA is a single banner and sizeB are 2 banners.

The problem is the time to display the banners in the right places. For this I need to repeat the same loop above to get the divs and another loop in the result to get the position in the array.

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

    
asked by anonymous 06.12.2014 / 06:13

1 answer

1

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

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 saving the elements in the first (and only) .each() of the DOM:

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;});
    }
});
    
06.12.2014 / 12:29