等待$.post完成

4

看起来我的脚本不想等待$.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调用完成后才继续进行?希望得到一些不太复杂的方法。:)


3
提供一个回调函数。Ajax 是异步的,浏览器不会等待响应结果返回! - Felix Kling
@zod - 在我的代码周围添加括号会使它看起来非常丑陋,不过这是唯一的方法吗? - Jeff
1
@jeff - 可运行的代码比漂亮的代码更好(但差别不大) - zsalzbank
@Jeff:我认为@zod的意思是你缺少括号。你的代码有语法错误。 - Felix Kling
@Jeff - 你可以创建一个函数来处理回调,而不是使用匿名函数,这样可以使代码更加简洁。 - matthewnessworthy
显示剩余3条评论
5个回答

4
使用回调函数正确地,可以让代码不显得太混乱。
只需在.post()调用之外创建一些函数,并在适当的时候在.post()中调用它们。您可以创建多个回调函数并以非常灵活的方式在AJAX调用中使用它们。
在您的情况下,因为您仅调用alert(),所以无需创建其他函数 - 只需在.post()调用中调用alert()即可。如果您的代码变得更大,请考虑创建单独的函数。
这就是JavaScript和异步调用的工作原理。适应它并利用其强大的功能编写非常干净和易于维护的代码。

那么在代码顶部定义一个函数,然后将其用作回调而不是匿名函数? - Jeff
@Jeff,实际上你是可以这样做的,但我建议在匿名函数内部调用它。这意味着你可以在这个匿名函数内部检查一个条件,并根据检查结果调用MyFunction1MyFunction2中的任何一个。这清楚明白吗?还是需要一些示例来说明如何操作? - Tadeck
@Jeff,我很高兴能帮到你 :) 在你的示例中,你也可以使用一个回调函数,传递truefalse。如果您有其他问题,请随时提出。 - Tadeck

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

这个更接近了,但还是不对。你在最后两行缺少了右括号。 - zsalzbank
最好将其包装在匿名函数中,以保持作用域的整洁。考虑到大多数情况下,您会将代码放置在一个$(document).ready(function(){中。 - PeeHaa

0

0

太乱了吗?如果你缩进超过一个空格,一切都会更加可读,而且仍然正常工作。

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();
});

虽然它很丑陋。


0

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");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接