jQuery中的多个AJAX请求 [英] Multiple AJAX requests in jQuery

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

问题描述

我有一个功能,提取数据从两个位置,并将上被显示给用户的模态对话框返回内容

两个请求是异步的,因为他们是跨域。问题在于,我不想,直到两个请求已完成加载,显示模式。如何检查,以确保这两个请求已完成加载模态过吗?

我试图放置openModal功能,在第二请求的成功处理程序并且工作时所述第一请求完成加载第二请求之前,但有时情况并非如此。

下面是我的code复制:

 函数loadData(ID){
$阿贾克斯({
    键入:GET,
    网址:https://someurl.com/v1.0/controller1/'+ ID,
    数据类型:JSONP,
    成功:功能(数据){
        //做一些东西到数据
    }
});

$阿贾克斯({
    键入:GET,
    网址:https://someurl.com/v1.0/controller2/'+ ID,
    数据类型:JSONP,
    成功:功能(数据){
        //做一些东西到数据

        openModal();
    }
});
}

传播openModal(){
//打开模态
}
 

解决方案

查看新版本的jQuery - 1.5。它支持正是你的问题,你可以看看这篇博客为你的问题的解决办法:<一href="http://www.erichynds.com/jquery/using-deferreds-in-jquery/">http://www.erichynds.com/jquery/using-deferreds-in-jquery/

I have a function that pulls data from two locations and places the returned content on a modal dialog that is displayed to the user.

Both requests are asynchronous because they're cross-domain. The problem lies in that I don't want to display the modal until both requests have finished loading. How can I check to make sure both requests have finished before loading the modal?

I have tried placing the openModal functions in the success handler of the second request and that works when the first requests finishes loading before the second request, but sometimes this isn't the case.

Here's a copy of my code:

function loadData(id) {
$.ajax({
    type: 'GET',
    url: 'https://someurl.com/v1.0/controller1/' + id,
    dataType: 'jsonp',
    success: function(data) {
        // Do some stuff to the data
    }
});

$.ajax({
    type: 'GET',
    url: 'https://someurl.com/v1.0/controller2/' + id,
    dataType: 'jsonp',
    success: function(data) {
        // Do some stuff to the data

        openModal();
    }
});
}

function openModal() {
// Open the modal
}

解决方案

Check out the new version of jQuery -- 1.5. It has support for exactly your problem, you can check out this blog post for the solution of your problem: http://www.erichynds.com/jquery/using-deferreds-in-jquery/

这篇关于jQuery中的多个AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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