views:

93

answers:

3

Let's say on ajax success the function: xmlParser(xml) is called and the XML response contains about 1500 xml elements (for example: ...)

Inside it looks like:

function xmlParser(xml){
    var xmlDOM = $(xml);  // dom object containing xml response

    xdom.find("book").each(function(){
        var $node = $(this);
        // parsing all the <book> nodes
    });
}

How can you say: parse only first 20 nodes from the xml response, do something with them. And you have a button,..when clicked parses the next 20 nodes...and so on.

So bassically, is there something like: children(20)....and a function wich will parse the next 20 nodes onClick.

thx

+3  A: 

You can implement simple pagination on your xmlParser function. Try something like this:

function xmlParser(xml, page, perpage){
    // dom object containing xml response
    var xmlDOM = $(xml);

    // From what index to start showing
    var start = (page - 1) * perpage;

    // Find elements starting from start point using .gt() up to end point using .lt()
    xmlDOM.find("book").gt(start - 1).lt(perpage).each(function() {
        var $node = $(this);
        // Do your stuff
    });
}

// Usage
xmlParser(xml, 1, 20);

That would only handle the given amount of items on given page. Note that this example does not take into account minimum and maximum page counts etc, but should give you something to work on.

But as David V. noted in the comments, you really should just fetch the correct amount of results from the server in the first place rather than parse them in JS. Currently, you're downloading all of the 1500 records even if the user wants only the first 20.

Tatu Ulmanen
xmlDOM.find("book").gt(start - 1) gives you a new collection, simply add .lt(perpage) after .gt(start - 1) should maximize the results to 20.
Fabian
@Fabian, yea, I noted that. Fixed :)
Tatu Ulmanen
thank you guys..
Johua
+2  A: 

This should do the work:

xdom.find("book:gt(lowerBound):lt(upperBound)").each(function(){
    var $node = $(this);
    // parsing all the <book> nodes
});

Where lowerBound and upperBound are your bounds.

Artem Barger
simple and beautifull
Johua
+1  A: 

I would store that data global on either a variable or jQuery'ish, with data.

function xmlParser(xml){
    $.data(document.body, 'xmlDOM', $(xml));  // dom object containing xml response      
});}

and then second function like

function getBooks(start, end){
  return($.data(document.body, 'xmlDOM').slice(start, end));
});

usage:

var books = getBooks(0,20);
 $.each(books, function(i){
   // do anything with objects, $('#something').append($(this));
 });

Kind Regards, --Andy

jAndy
awsome and thanks a lot!
Johua