jQuery:等待直到成功处理了多个GET请求 [英] jQuery: Wait till multiple GET requests are successully processed

查看:149
本文介绍了jQuery:等待直到成功处理了多个GET请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要发出多个$ .get请求,处理它们的响应,并将处理结果记录在同一数组中.代码如下:

I need to issue multiple $.get requests, process their responses, and record the results of the processing in the same array. The code looks like this:

$.get("http://mysite1", function(response){
  results[x1] = y1;
}
$.get("http://mysite2", function(response){
  results[x2] = y2;
}

// rest of the code, e.g., print results

在继续执行我的其余代码之前,是否仍要确保所有成功功能都已完成?

Is there anyway to ensure that all the success functions have completed, before I proceed to the rest of my code?

推荐答案

有一个非常优雅的解决方案:jQuery Deferred对象. $ .get返回一个实现Deferred接口的jqXHR对象-可以像这样组合这些对象:

There is a very elegant solution: the jQuery Deferred object. $.get returns a jqXHR object that implements the Deferred interface - those objects can be combined like this:

var d1 = $.get(...);
var d2 = $.get(...);

$.when(d1, d2).done(function() {
    // ...do stuff...
});

请访问 http://api.jquery.com/category/deferred-object/了解更多信息,并 http://api.jquery.com/jQuery.when/

Read more at http://api.jquery.com/category/deferred-object/ and http://api.jquery.com/jQuery.when/

这篇关于jQuery:等待直到成功处理了多个GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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