简体   繁体   中英

jquery $.GET loading order

I am loading all external pages in jquery for a slider. The problem is it loads in a different order. What I need to do is sequence the loading of pages

$.get("page1.php", function( my_var ) {
    $('#slider').append($('.content', my_var));
});
$.get("page2.php", function( my_var ) {
    $('#slider').append($('.content', my_var));
});
$.get("page3.php", function( my_var ) {
    $('#slider').append($('.content', my_var));
});

sometimes page3 loads before page2.

It happens because your are dealing with asynchronous execution. The order of the Ajax calls is not guaranteed. Call every $.get inside the callback of the previous one. Something like:

$.get("page1.php", function( my_var1 ) {
    $('#slider').append($('.content', my_var1 ));
    $.get("page2.php", function( my_var2 ) {
        $('#slider').append($('.content', my_var2 ));
        $.get("page3.php", function( my_var3 ) {
            $('#slider').append($('.content', my_var3 ));
        });
    });
});

You could load one by one.

$.get("page1.php", function( my_var ) {
    $('#slider').append($('.content', my_var));
    $.get("page2.php", function( my_var ) {
        $('#slider').append($('.content', my_var));
        $.get("page3.php", function( my_var ) {
              $('#slider').append($('.content', my_var));
         });
    });
});

Or if you could use a wrap container, you could use .load method, which allows you use a selector in the url. And this solution will let 3 contents load at same time, but the position is fixed.

var slider = $('#slider');
$('<div>').appendTo(slider).load('page1.php .content');
$('<div>').appendTo(slider).load('page2.php .content');
$('<div>').appendTo(slider).load('page3.php .content');

It works like this because $.get is asynchronous method (it is a shorthand for ajax request). You can use $.when method to test wheter request was done:

var getPage1 = $.get("page1.php", function( my_var ) {
    $('#slider').append($('.content', my_var));
});

// you can pass 1 or more deffereds
$.when(getPage1).done(function() {
    // do something
});

You can try to nest the calls. When page finishes loading, load the next one.. Something like this:

$.get("page1.php", function( my_var ) {
    $('#slider').append($('.content', my_var));
    $.get("page2.php", function( my_var ) {
        $('#slider').append($('.content', my_var));
        $.get("page3.php", function( my_var ) {
            $('#slider').append($('.content', my_var));
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM