Christian Isai
Christian Isai

Reputation: 146

optimize ajax call

I need to grab several items from other page right now my jquerycalls looks like this

$('.slide1 .pic').load('url div.zoomPad');
$('.slide1 .title').load('url .pname');
$('.slide1 .other').load('url .anotherdiv');

.. and so on.. is there a way to make just 1 call and grab all elements? and then place them where I want?

im going to do 7 calls in 7 different pages so I dont think it would be a good Idea to make the calls like that .. there should be a cleaner way.. do you know any?

Upvotes: 2

Views: 1099

Answers (3)

Matt Bradley
Matt Bradley

Reputation: 4505

Try something like this:

$('<div/>').load('url', function() {
    $('.slide1 .pic').html($(this).find('div.zoomPad'));
    $('.slide1 .title').html($(this).find('.pname'));
    $('.slide1 .other').html($(this).find('.anotherdiv'));
});

Basically, we do one Ajax call and store the response in a jQuery object. Then we can use .find() to parse the response to get what we want.

Upvotes: 1

gdoron
gdoron

Reputation: 150313

Yes there is the ajax function for lower level:

$.ajax({
  url: "test.html",
  dataType: json 
  success: function(data){
    $('.first').val(data.first);
    $('.second').val(data.second);
    //...
    $('.n').val(data.n); // Sorry for the n part, 
                        // I have a test in Linear algebra soon...
  }
});

Make sure the server returns the data as json format, and you ready to go with easiest way.

docs

Upvotes: 2

James Montagne
James Montagne

Reputation: 78760

You can use .ajax instead of .load and handle the response yourself in the success handler.

$.ajax({...
    success: function(data){
        $('.slide1 .pic').html($(data).find('div.zoomPad'));
        // etc.
    ...
});

Upvotes: 4

Related Questions