Javascript/jQuery中的并行Ajax调用
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: 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/在那里你可以清楚地看到关于async的信息。默认异步参数值为true。
默认情况下,所有请求都是异步发送的(即,默认情况下设置为true)。如果需要同步请求,请将此选项设置为false。跨域请求和数据类型:"jsonp"请求不支持同步操作。请注意,同步请求可能会暂时锁定浏览器,从而在请求处于活动状态时禁用任何操作。。。
以下对我有效-我有多个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
}
在jQuery.ajax中,您应该提供如下回调方法:
j.ajax({
url : url0,
async : true,
dataType : 'json',
success:function(data){
console.log(data);
}
}
或者你可以直接使用
jQuery.getJSON(url0, function(data){
console.log(data);
});
参考
您将无法像您的示例那样处理它。设置为async会使用另一个线程在上发出请求,并让您的应用程序继续运行。
在这种情况下,您应该使用一个新函数来绘制区域,然后使用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;
}
});
这应该奏效。
以下是您的问题的解决方案:http://jsfiddle.net/YZuD9/
您可以将不同ajax函数的所有功能组合到一个ajax函数中,或者从一个ajax功能中调用其他函数(在这种情况下,它们将是私有/控制器端),然后返回结果。Ajax调用确实有点停滞,所以要尽量减少它们。
您还可以使ajax函数异步(这样会像正常函数一样工作),然后在所有函数返回数据后,您可以在最后渲染图形。
- 无法在通过jQuery的ajax加载的页面中执行javascript
- Javascript/jQuery中的并行Ajax调用
- 并行或串行编写多个 AJAX 调用是否更好
- 并行 AJAX 调用 - 无法接收来自第一个的响应
- Ajax/Jquery - 在从服务器返回数据时调用 javascript 函数/使用 ajax 执行并行 SQL 查询
- 使用 tokenInput 进行两个并行 AJAX 调用
- 并行 ajax 请求还是 sql 查询?[性能方面]
- 是否有管理并行AJAX查询的设计模式
- 使用ajax进行并行页面加载
- 无法从并行ajax调用中检索数据
- jQuery并行AJAX调用混淆了返回值
- 当$.ajax()不起作用时,并行调用$
- 调用多个ajax调用与Jquery延迟时,然后(3个并行调用,然后完成一个ajax调用)
- 在优先级AJAX请求的情况下,如何处理浏览器对每个域并行请求的限制
- 并行ajax调用-行为类似于多线程系统
- AJAX 请求不使用 $.when(..) 并行执行
- 并行执行多个AJAX请求,并在所有请求完成后运行一个函数
- 如何查找在并行ajax调用期间导致错误的方法
- vadin javascript扩展中的并行AJAX调用
- JSONP Ajax调用不能并行工作