jQuery / Javascript execution order?
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:
- Onload - get() function (retrieves data for both divs)
- The move() function is开发者_JAVA百科 activated via a button
- move.php has the mysql_query update action
- 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.
精彩评论