问题描述
我对JavaScript / jQuery世界完全陌生,需要一些帮助。现在,我正在写一个HTML页面,我必须做5个不同的Ajax调用来获取数据来绘制图表。现在,我将这5个ajax调用称为:
I am completely new to Javascript/jquery world and need some help. Right now, I am writing one html page where I have to make 5 different Ajax calls to get the data to plot graphs. Right now, I am calling these 5 ajax calls like this:
$(document).ready(function() {
area0Obj = $.parseJSON($.ajax({
url : url0,
async : false,
dataType : 'json'
}).responseText);
area1Obj = $.parseJSON($.ajax({
url : url1,
async : false,
dataType : 'json'
}).responseText);
.
.
.
area4Obj = $.parseJSON($.ajax({
url : url4,
async : false,
dataType : 'json'
}).responseText);
// some code for generating graphs
)} // closing the document ready function
我的问题是在上面的场景中,所有的ajax调用都是串行的。也就是说,1次调用完成2次启动后,2次完成3次启动等等。每个Ajax调用大约需要大约5 - 6秒才能获取数据,这会使整个页面在大约30秒内加载。
My problem is that in above scenario, all the ajax calls are going serially. That is, after 1 call is complete 2 starts, when 2 completes 3 starts and so on .. Each Ajax call is taking roughly around 5 - 6 sec to get the data, which makes the over all page to be loaded in around 30 sec.
我尝试将异步类型设置为true,但在这种情况下,我没有立即获取数据来绘制破坏我目的的图表。
I tried making the async type as true but in that case I dont get the data immediately to plot the graph which defeats my purpose.
我的问题是:
如何让这些调用并行,以便我可以并行地获取所有这些数据,并且可以在更短的时间内加载我的页面?
My question is:How can I make these calls parallel, so that I start getting all this data parallely and my page could be loaded in less time?
在此先感谢。
推荐答案
com / jQuery.when /> jQuery.when (deferreds):
Using jQuery.when (deferreds):
$.when( $.ajax("/req1"), $.ajax("/req2"), $.ajax("/req3") ).then(function(resp1, resp2, resp3){
// plot graph using data from resp1, resp2 & resp3
});
只有当所有3个ajax调用完成时才会调用回调函数。
callback function only called when all 3 ajax calls are completed.
这篇关于并行Ajax调用Javascript / jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!