[英]Parallel Ajax Calls in Javascript/jQuery
我对Javascript / jquery领域完全陌生,需要一些帮助。 现在,我正在编写一个html页面,在这里我必须进行5个不同的Ajax调用才能获取数据以绘制图形。 现在,我正在这样调用这5个ajax调用:
$(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秒左右的时间内被加载。
我试图使异步类型为true,但在那种情况下,我没有立即获得数据来绘制图,这违背了我的意图。
我的问题是:如何使这些调用并行进行,以便开始并行获取所有这些数据,并且可以在更短的时间内加载页面?
提前致谢。
使用jQuery.when (延迟):
$.when( $.ajax("/req1"), $.ajax("/req2"), $.ajax("/req3") ).then(function(resp1, resp2, resp3){
// plot graph using data from resp1, resp2 & resp3
});
仅在完成所有3个ajax调用时才调用回调函数。
您不能使用async: false
来执行此操作async: false
如您所知,代码是同步执行的(即,直到上一个操作完成才开始执行操作)。
您将需要设置async: true
(或忽略它-默认情况下为true)。 然后为每个AJAX调用定义一个回调函数。 在每个回调内部,将接收到的数据添加到数组中。 然后,检查是否所有数据都已加载( arrayOfJsonObjects.length == 5
)。 如果有的话,调用一个函数对数据做任何想做的事情。
让我们尝试以这种方式做到这一点:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var area0Obj = {responseText:''};
var area1Obj = {responseText:''};
var area2Obj = {responseText:''};
var url0 = 'http://someurl/url0/';
var url1 = 'http://someurl/url1/';
var url2 = 'http://someurl/url2/';
var getData = function(someURL, place) {
$.ajax({
type : 'POST',
dataType : 'json',
url : someURL,
success : function(data) {
place.responseText = data;
console.log(place);
}
});
}
getData(url0, area0Obj);
getData(url1, area1Obj);
getData(url2, area2Obj);
});
</script>
如果服务器端将是smth。 像这样:
public function url0() {
$answer = array(
array('smth' => 1, 'ope' => 'one'),
array('smth' => 8, 'ope' => 'two'),
array('smth' => 5, 'ope' => 'three')
);
die(json_encode($answer));
}
public function url1() {
$answer = array('one','two','three');
die(json_encode($answer));
}
public function url2() {
$answer = 'one ,two, three';
die(json_encode($answer));
}
因此,如您所见,在那里创建了一个用于从服务器获取数据的函数getData(),然后调用了3次。 结果将以异步方式接收,因此,例如,第一个可以获得第一个呼叫的答案,而第一个可以获得第一个呼叫的答案。
控制台答案将是:
[{"smth":1,"ope":"one"},{"smth":8,"ope":"two"},{"smth":5,"ope":"three"}]
["one","two","three"]
"one ,two, three"
PS。 请阅读: http : //api.jquery.com/jQuery.ajax/,在那里您可以清楚地看到有关异步的信息。 默认异步参数值= true。
默认情况下,所有请求都是异步发送的(即默认情况下设置为true)。 如果需要同步请求,请将此选项设置为false。 跨域请求和dataType:“ jsonp”请求不支持同步操作。 请注意,同步请求可能会暂时锁定浏览器,从而在请求处于活动状态时禁用任何操作...
在jQuery.ajax中,您应该提供如下的回调方法:
j.ajax({
url : url0,
async : true,
dataType : 'json',
success:function(data){
console.log(data);
}
}
或者你可以直接使用
jQuery.getJSON(url0, function(data){
console.log(data);
});
您将无法像您的示例一样处理它。 设置为异步会使用另一个线程来发出请求,并让您的应用程序继续。
在这种情况下,您应该利用一个新函数来绘制一个区域,然后使用ajax请求的回调函数将数据传递给该函数。
例如:
$(document).ready(function() {
function plotArea(data, status, jqXHR) {
// access the graph object and apply the data.
var area_data = $.parseJSON(data);
}
$.ajax({
url : url0,
async : false,
dataType : 'json',
success: poltArea
});
$.ajax({
url : url1,
async : false,
dataType : 'json',
success: poltArea
});
$.ajax({
url : url4,
async : false,
dataType : 'json',
success: poltArea
});
// some code for generating graphs
}); // closing the document ready function
看来您需要异步分派请求并定义一个回调函数来获取响应。
按照这种方式,它将等待直到成功分配了变量(意味着:响应刚刚到达),直到它继续分派下一个请求。 只是使用这样的东西。
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(data) {
area0Obj = data;
}
});
这应该可以解决问题。
您可以将不同ajax函数的所有功能组合到1个ajax函数中,或从1个ajax函数中组合,调用其他函数(在这种情况下,它们将是私有/控制器端),然后返回结果。 Ajax调用确实会停顿一点,因此尽量减少它们。
您还可以使ajax函数成为异步函数(其行为类似于普通函数),然后在所有函数返回其数据之后,在最后渲染图形。
这是您问题的解决方案: http : //jsfiddle.net/YZuD9/
以下对我有用-我有多个ajax调用,需要传递序列化对象:
var args1 = {
"table": "users",
"order": " ORDER BY id DESC ",
"local_domain":""
}
var args2 = {
"table": "parts",
"order": " ORDER BY date DESC ",
"local_domain":""
}
$.when(
$.ajax({
url: args1.local_domain + '/my/restful',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST",
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(args1),
error: function(err1) {
alert('(Call 1)An error just happened...' + JSON.stringify(err1));
}
}),
$.ajax({
url: args2.local_domain + '/my/restful',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST",
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(args2),
error: function(err2) {
calert('(Call 2)An error just happened...' + JSON.stringify(err2));
}
})
).then(function( data1, data2 ) {
data1 = cleanDataString(data1);
data2 = cleanDataString(data2);
data1.forEach(function(e){
console.log("ids" + e.id)
});
data2.forEach(function(e){
console.log("dates" + e.date)
});
})
function cleanDataString(data){
data = decodeURIComponent(data);
// next if statement was only used because I got additional object on the back of my JSON object
// parsed it out while serialised and then added back closing 2 brackets
if(data !== undefined && data.toString().includes('}],success,')){
temp = data.toString().split('}],success,');
data = temp[0] + '}]';
}
data = JSON.parse(data);
return data; // return parsed object
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.