我有一个load_graphs函数,它会在AJAX调用中创建一个图形。
需要多次调用load_graphs
函数以生成不同区域的句点,如下所示。
即使使用包装函数顺序完成调用,它也称为异步。如何逐个调用相同的AJAX函数。
function load_all_graphs(){
load_graphs('national','','container-natl-rates','container-natl-counts')
load_graphs('division','Western','container-west-rates','container-west-counts')
}
load_all_graphs()
var load_graphs = function(scope, scopeFilter, chart_1, chart_2){
d = new Date()
starttime = d.setMonth(d.getMonth()-1)
starttime = d.setDate(d.getDate()-1)
endtime = (new Date).getTime()
// console.log('starttime == ', starttime)
// console.log('endtime == ', endtime)
if (scope == 'national'){
url = 'http://99.88.53.222:8081/vp.0.1-SNAPSHOT/Metrics?scope='+ scope + '&interval=day&startTime='+starttime+'&endTime='+ endtime
}else {
url = 'http://99.88.53.222:8081/vp.0.1-SNAPSHOT/Metrics?scope=' + scope + '&scopeFilter=' + scopeFilter + '&interval=day&startTime='+starttime+'&endTime='+ endtime
}
if (scopeFilter == ''){
data_filter = 'national'
}
else if (scopeFilter == 'Western'){
data_filter = 'Western'
}
$.ajax({type:'GET',
url: url,
// async: false,
success: function(data){
// console.log(JSON.stringify(data))
// console.log(data)
$.each(data,function(i,x){
console.log('national == ', x[0]['X1'])
console.log('national data_filter == ', data_filter)
console.log('national == ', x[0]['X1'][data_filter])
for (var i = 0; i <= 10; i++)
{
error_counts_results[i] = []
}
$.each(x[0]['X1'][data_filter], function(unix_date,data){
if (parseFloat(unix_date)){
$.each(error_constants,
function(ix,error_item){
// console.log(ix)
// console.log(data[error_item])
error_counts_results[ix].push([parseInt(unix_date),data[error_item]])
}
)
// console.log('result == ', JSON.stringify(error_counts_results))
}
})
})
seriesOptions[0] = {
name: error_constants[5],
data: error_counts_results[5]
};
console.log('option 1 == ', seriesOptions[0])
seriesOptions[1] = {
name: error_constants[0],
data: error_counts_results[0]
};
console.log('option 2 == ', seriesOptions[1])
seriesOptions[2] = {
name: error_constants[3],
data: error_counts_results[3]
};
console.log('option 3 == ', seriesOptions[2])
params = {
'title':'National'
,'y2axis':'pct'
}
createChart_National(chart_1,params);
seriesOptions[0] = {
name: error_constants[4],
data: error_counts_results[4]
};
seriesOptions[1] = {
name: name,
data: error_counts_results[1]
};
seriesOptions[2] = {
name: name,
data: error_counts_results[2]
};
params = {
'title':'National'
,'y2axis':'cnt'
}
createChart_National(chart_2,params);
},
})
}
答案 0 :(得分:0)
你可以使用promises将你的ajax调用链接在一起,jQuery已经将它内置到ajax函数中。
$.ajax({ // ... })
.then (function (arg)
{
// do something with arg
})
.then (function(){
return $.ajax({ }); // second ajax call, return the promise
})
.done (function(args)
{
// do something with your final result
});
如果要并行运行请求,请查看使用promise.all
一般情况下,我会建议阅读有关承诺的内容,这里是开始http://dailyjs.com/2014/02/20/promises-in-detail/
的好地方