how to use jquery to load from array of pages - in

2019-08-28 13:11发布

问题:

I'm grabbing a bunch of links from a page and then pulling in a specific content element from those pages. The code I just created works and does just that.

The problem is because the requests are asynchronous, the elements are not loading up in order. I tried adding a delay but that didn't work.

Do I need to be using .ajax instead of .load? If so, what would this looped append look like with .ajax command? Can you still use a selector with the url? Or is there an effective way to acheive this with .load?

Thanks in advance.

    function runthis() {

var links = $("#article-slide-belt a").map(function() {
                return this.href;
            }).get();

$.each( links, function(i, l){

    $("<div>").load(l + " .gl_left", function() {
          $(".gl_left").append($(this).find(".gl_left").html());
    });

 });

}

回答1:

Perhaps this: http://plugins.jquery.com/project/ajaxqueue



回答2:

You could specify the next link to load on completion of the first request - the code below is not very elegant but it will do what you want

var links
var content_index=0;
$(document).ready( function() {
    links = $("#article-slide-belt a").map( function() {
        return this.href;
    }).get();
    loadContent()
})
function loadContent() {
    if (content_index<links.length) {
        $("div").load(links[content_index] + " .gl_left", function() {
            $(".gl_left").append($(this).find(".gl_left").html());
            content_index++;
            loadContent();
        });
    }
}


回答3:

I tried the synchronous .ajax route. And it comes in correct order but the wait is unbearable. Needs to be readable page while the data is loading in.

$.each( links, function(i, l){

$.ajax({        
     url: l,                         
     async: false,         
     success: function(data){
    var $response=$(data);

    $(".gl_left").append($response.find(".gl_left").html());

    }     
     });

 });