等待$。员额完成 [英] Waiting for $.post to finish

查看:126
本文介绍了等待$。员额完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看来,我的脚本不希望等待$。员额调用来完成。这就是一个问题。下面是一些伪code:

It appears that my script does not want to wait for the $.post call to finish. Thats a problem. Here is some pseudo code:

<script type="text/javascript" language="javascript">
$(document).ready(function(){
  // Global var, to be used everywhere in the ready scope 
  // Note its default value!    
  var test = false;
  $.post('test.php',{},function(result){
   if(result=='yes')
   {
    // This gets executed!
    alert('Its true! Hurraaay!');
    test = true;
   }
   else
   {
    test = false;
   }
  }

  if(test==false)
  {
   // THIS gets executed, despite the fact that we set test to true!
   alert('Awww....');
  }
  // it reaches this, showing us that there was no error!
  alert('Im alive!!!');
  // and a whoooole bunch of other code here...
}
</script>

什么是要确保我的帖子通话结束后继续之前,没有挂在浏览器的最佳方法是什么?希望的东西,是不是太乱了。 :)

What is the best way to make sure that my Post call is finished before continuing, without hanging the browser? Hoping for something that is not too messy. :)

推荐答案

不是太乱用回调正常。

刚刚创建。员额()通话之外的一些功能,并在。员额称之为()当你认为这是适当的。你让很多回调,并利用它们内部的AJAX在一个非常灵活的方式调用。

Just create some function outside the .post() call and call it inside .post() when you think it is appropriate. You make many callbacks and use them inside the AJAX calls in a really flexible way.

在你的情况,因为你只叫警报(),也没有必要建立额外的功能 - 只需拨打警报()。员额()通话。如果你的code变大了,考虑创建独立的功能。

In your case, because you only call alert(), there is no need to create additional functions - just call alert() inside .post() call. If your code gets bigger, consider creating separate functions.

这是JavaScript和异步调用的工作方式。习惯了它,并利用其权力来写的很干净,维护code。

This is how JavaScript and asynchronous calls work. Get used to it and use its power to write very clean and maintainable code.

这篇关于等待$。员额完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆