javascript 等待 $.post 完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6230964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:00:20  来源:igfitidea点击:

Waiting for $.post to finish

javascriptjqueryajaxpost

提问by Jeff

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

看来我的脚本不想等待 $.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>

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. :)

在继续之前确保我的 Post 调用完成而不挂起浏览器的最佳方法是什么?希望不要太乱。:)

回答by Tadeck

Not too messy is using callbacks properly.

正确使用回调不会太乱。

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.

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

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.

在您的情况下,因为您只调用alert(),所以不需要创建额外的函数 - 只需在 callalert()内部.post()调用。如果您的代码变大,请考虑创建单独的函数。

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

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

回答by morpheus

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

回答by Matt Evanoff

回答by brymck

Too messy? If you indent more than one space everything is much more readable and still works fine.

太乱?如果你缩进不止一个空格,一切都会更易读并且仍然可以正常工作。

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

Hideous though it is.

虽然很可怕。

回答by Bahl

The JQuery .post() method asynchronously connects to your server script. You utilize the callback feature in order for the program to make use of the data once the response is returned from the script.

JQuery .post() 方法异步连接到您的服务器脚本。您可以利用回调功能,以便程序在脚本返回响应后使用数据。

Instead of attempting to processing the data synchronously after the call to post, process the data when the response is received. Utilize functions to make your code more readable.

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

$(function() {
    postTest();
});

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

function testSuccess() {
    alert("Success");
}

function testFailure() {
    alert("Failure");
}