简体   繁体   中英

The loading order of Js code and ajax request of Jquery in the Dom

function f(){
$.post('1.php',{},function(){window.location.href="../../2.php";});
}

When click a button,excute the function f.The code above can run correctly and achieve the wanted function.But when the code changes into the follow format:

function f(){
$.post('1.php',{},function(){});
window.location.href="../../2.php";
}

the ajax request will not work.I know it has something to do with the Javascript load order,but I want to make it clear in a deep level.It is very nice of you to help me and explain it in detail.Thank you!

When you have

$.post('1.php',{},function(){});
window.location.href="../../2.php";

the second line is executed as soon as the first one has been executed. But the first statement only launches the ajax request, it doesn't block until the browser has really sent the whole request to the server.

As this second line replaces the page, it also stops the script and tells the browser it can stop what it was being doing for the page, like querying a server.

The solution is what you have in your first code :

$.post('1.php',{},function(){window.location.href="../../2.php";});

the window.location change is only done when the browser has received the answer.

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