Randy C
Randy C

Reputation: 47

How to load the same div from multiple pages, using Jquery

I'm trying to put together a script that will add to the concept of load, and extend it outward in a fashion that load can be called to multiple pages, in search of instances of a div.

For example, consider the code below:

<div class="loadStuffHere">
</div>

$('.loadStuffHere').load('/wiki.htm .posts');

So, the code above works just fine, but I'm not sure how to get it to search more than one page at a time.

The second page I would need to search in this case would be: /wiki.htm?b=1&pageindex=2. After the script searches the first page, then it would need to search the second. After the second page is searched, then the script would need to first auto increment the number 2, and change it to a three, and search that page, and then continue to do so, until it hits a page that doesn't exist, and then return false and end it's execution. So the search and load process would consist of this:

/wiki.htm
/wiki.htm?b=1&pageindex=2
/wiki.htm?b=1&pageindex=3
/wiki.htm?b=1&pageindex=4
/wiki.htm?b=1&pageindex=5
/wiki.htm?b=1&pageindex=6

And it would continue in that manor, until it hits a page that doesn't exist yet, as this is a pagination system.

Is this something that can be done, and if so, what would it look like? Any help is very appreciated!

P.s. If you are thinking I'm likely attempting something that would be easier achieved with some server side coding, you are right. I don't have access to it however, regretfully.

Upvotes: 3

Views: 518

Answers (2)

Derek
Derek

Reputation: 4751

You could do something like:

function loadWikiPosts(page_index) {
    if (page_index != null) { url += '?b=1&pageIndex='+page_index; }
    else { page_index = 1; /* for next time if this one fails */ }

    url += ' .posts'; // to grab just the posts

    // Send the AJAX request
    $('.loadStuffHere').load(url, function(response, status, request) {
        if (status == "error") { console.log(response); throw "Load returned an error"; }
        if ($('.loadStuffHere').find('.posts').length == 0) {
            page_index++;
            loadWikiPosts(page_index);
        }
    });
}

try {
    loadWikiPosts();
} catch (exception) {
    // do something w/the exception message
}

Upvotes: 1

Jeff Noel
Jeff Noel

Reputation: 7618

Create an array with all your results, using the following code:

JavaScript/jQuery

var linkArray=["/wiki.htm",
  "/wiki.htm?b=1&pageindex=2",
  "/wiki.htm?b=1&pageindex=3",
  "/wiki.htm?b=1&pageindex=4",
  "/wiki.htm?b=1&pageindex=5",
  "/wiki.htm?b=1&pageindex=6"];


for (var i in linkArray)
{
    var content = "";
    $('.loadStuffHere').append($(content).load(linkArray[i]+' .posts'));
}

The code above was not tested.

Upvotes: 1

Related Questions