开发者

jQuery / Javascript execution order?

开发者 https://www.devze.com 2023-03-21 03:00 出处:网络
I\'m trying to exactly figure out the execution order of what is going on here. I\'m using jquery to retrieve new data, and I get occasional irregularities. How I have its current work flow order shou

I'm trying to exactly figure out the execution order of what is going on here. I'm using jquery to retrieve new data, and I get occasional irregularities. How I have its current work flow order should be something like this:

  1. Onload - get() function (retrieves data for both divs)
  2. The move() function is开发者_JAVA百科 activated via a button
  3. move.php has the mysql_query update action
  4. Reload the div with the updated database information.

function get(varpass) {
    varpass = typeof(varpass) != 'undefined' ? varpass : "all";
    var j = "<?=$_SESSION['username']?>";
    if (varpass == "all" || varpass == "left") {
        $('#left').hide();
        $.get('data.php', {
            name: j,
            p: varpass
        }, function (output) {
            $('#left').html(output).fadeIn(250);
        });
    }
    if (varpass == "all" || varpass == "main") {
        $('#main').hide();
        $.get('main.php', {
            name: j,
            p: varpass
        }, function (output) {
            $('#main').html(output).fadeIn(250);
        });
    }
}
$(document).ready(function () {
    get("all");
});
function move(p) {
    var j = "<?=$_SESSION['username']?>";
    $.get('move.php', {
        name: j,
        p: p
    }, function (output) {
        $('#debug').html(output).fadeIn(1);
    });
    $('#main').hide();
    get("main");
}

I find that on occasion the div will retrieve information before the move.php mysql_query has been completed. How can control the order of execution better? I want the information to finish being updated before it calls to retrieve the data from the database again.

Thanks


I believe the execution order is working exactly as you expect, except for in the following snippet:

function move(p) {
    var j = "<?=$_SESSION['username']?>";
    $.get('move.php', {
        name: j,
        p: p
    }, function (output) {
        $('#debug').html(output).fadeIn(1);
    });
    $('#main').hide();
    get("main");  //this can/will happen before `move.php` completes
}

If you want the get("main"); to not happen until after your call to move.php completes, then you might have better luck with something like:

function move(p) {
    var j = "<?=$_SESSION['username']?>";
    $.get('move.php', {
        name: j,
        p: p
    }, function (output) {
        $('#debug').html(output).fadeIn(1);
        get("main");  //this won't happen until after `move.php` completes
    });
    $('#main').hide();
}

By moving the get("main"); to the response callback/handler, you can ensure that it will not be executed until after your other request has returned its response.

0

精彩评论

暂无评论...
验证码 换一张
取 消