我正在使用highcharts.js库来产生利润&我的网站的损失图表 我有一个数组,其值来自我服务器的ajax响应。
这就是代码:
<script type="text/javascript">
var profit = [];
$(document).ready(function(e) {
$.ajax({
url : "/php/get-inflow.php",
dataType: "json",
type: "POST",
success: function(data){
for(var i =0; i<data.length; i++){
if(data[i] == null){
profit[i] = 0;
}else{
profit[i] = data[i];
}
}
}
});
});
$(function () {
$('#profitloss').highcharts({
//some other highcharts code
series: [{
name: 'Inflow',
data: profit
}, {
name: 'Outflow',
data: [2, 2, 3, 2, 1,10,10,10,10,10,10,10]
}]
});
});
</script>
我认为数组(profit [])无法识别,或者这不是一种有效的方式?三江源!
答案 0 :(得分:2)
因为ajax调用是异步的,所以profit
数组在显示图表时仍为空(定义为[])。您必须将图表创建的代码移动到ajax success()
函数,如:
$(document).ready(function(e) {
$.ajax({
url : "/php/get-inflow.php",
dataType: "json",
type: "POST",
success: function(data){
for(var i =0; i<data.length; i++){
if(data[i] == null){
profit[i] = 0;
}else{
profit[i] = data[i];
}
}
$('#profitloss').highcharts({
//some other highcharts code
series: [{
name: 'Inflow',
data: profit
}, {
name: 'Outflow',
data: [2, 2, 3, 2, 1,10,10,10,10,10,10,10]
}]
});
}
});
});
另一种选择是制作绘制图表的功能:
function drawChart() {
$('#profitloss').highcharts({
series: [{
name: 'Inflow',
data: profit
}, {
name: 'Outflow',
data: [2, 2, 3, 2, 1,10,10,10,10,10,10,10]
}]
});
}
并在for
函数中的success()
循环后调用该函数:
success: function(data){
for(var i =0; i<data.length; i++){
if(data[i] == null){
profit[i] = 0;
}else{
profit[i] = data[i];
}
}
drawChart();
}