如何等待ajax调用返回 [英] how to wait for an ajax call to return

查看:80
本文介绍了如何等待ajax调用返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JQuery,尽管在执行更多代码之前,我正努力成功地等待ajax调用成功。有没有办法等待ajax打电话?我看过一些例子,但它似乎只是盲目等待x秒的数量?



谢谢,
James



  var bodyContent =>  $ .ajax({
url:script.php,
global:false,
type:POST,
data:{id:this.getAttribute('id ')},
dataType:html,
async:false,
success:function(msg){
alert(msg);
}
}
).responseText;

来源: http://api.jquery.com/jQuery.ajax/

然而,同步请求是一个倒退,因为JS引擎(以及某些浏览器中的用户界面)将阻塞,直到请求完成。 Douglas Crockford曾撰写有关同步请求的文章:

同步编程是不尊重的,不应在人们使用的应用程序中使用。


I'm trying to use JQuery although i'm struggling to successfully wait for a ajax call to succeed before executing further code. Is there a way to wait for an ajax to call? I've seen examples but it seems just to wait blindly for x amount of seconds?

Thanks, James

解决方案

Yes, you can do request synchronously:

var bodyContent = $.ajax({
      url: "script.php",
      global: false,
      type: "POST",
      data: {id : this.getAttribute('id')},
      dataType: "html",
      async:false,
      success: function(msg){
         alert(msg);
      }
   }
).responseText;

Source: http://api.jquery.com/jQuery.ajax/

However, synchronous requests are a step backwards, as the JS engine (and, in some browsers, the user interface) will block until the request completes. Douglas Crockford once wrote about synchronous requests:

Synchronous programming is disrespectful and should not be employed in applications which are used by people.

这篇关于如何等待ajax调用返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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