等待$ .post完成

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

 $(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... }  

在没有挂起浏览器的情况下,在继续之前确保我的Post调用完成的最佳方法是什么? 希望有一些不太乱的东西。 🙂

没有太麻烦正在使用回调。

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

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

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

  

是的,它不会等待。 看这里:

http://sofzh.miximages.com/javascript/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()方法异步连接到您的服务器脚本。 您可以使用回调function,以便程序在从脚本返回响应后使用数据。

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

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