正在等待$.post完成



我的脚本似乎不想等待$.post调用完成。这是个问题。这里有一些伪代码:

<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>

在不挂起浏览器的情况下,确保我的Post通话在继续之前完成的最佳方法是什么?希望得到一些不太乱的东西。:)

正确使用回调并不太麻烦。

只需在.post()调用之外创建一些函数,并在您认为合适的时候在.post()内部调用它。您可以进行许多回调,并以非常灵活的方式在AJAX调用中使用它们。

在您的情况下,因为您只调用alert(),所以不需要创建其他函数——只需在.post()调用中调用alert()即可。如果代码变大,可以考虑创建单独的函数。

这就是JavaScript和异步调用的工作方式。习惯它,并使用它的能力来编写非常干净和可维护的代码。

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

是的,它不等待。请参阅此处:

http://fixingthesejquery.com/images/ajax101.png

这里:

http://fixingthesejquery.com

太乱了?如果缩进多个空格,那么所有内容都会可读性更强,并且仍然可以正常工作。

var test = false; // NOW it's global
// Just so we can use the method again
function postSomething() {
  $.post('test.php', {}, function(result) {
    if(result === 'yes') {
      alert('Its true! Hurraaay!');
      test = true;
      alert('Im alive!!!');
    } else {
      test = false;
      alert('Awww....');
    }
  });
}
$(document).ready(function() {
  postSomething();
});

虽然很隐蔽。

JQuery.post()方法异步连接到服务器脚本。一旦从脚本返回响应,就可以利用回调功能使程序利用数据。

不要在调用post后尝试同步处理数据,而是在收到响应时处理数据。利用函数使代码更具可读性。

$(function() {
    postTest();
});
function postTest() {
    $.post(
        'test.php',
        {},
        function(response) {
            if(response == 'yes') {
                testSuccess();
            } else {
                testFailure();
            }
        }
    ); 
}
function testSuccess() {
    alert("Success");
}
function testFailure() {
    alert("Failure");
}

最新更新