近日在用highcharts做图表,通过Ajax请求获取json数据然后填充图表,原代码如下:
function select() {
x.splice(0, x.length);
y1.splice(0, y1.length);
y2.splice(0, y2.length);
y3.splice(0, y3.length);
var start = $("#start").val();
var end = $("#end").val();
var grain = $("#grain").val();
$.ajaxSetup({
data:{csrfmiddlewaretoken:$("#hidden").val()}
});
$.ajax({
url:'xxx',
type:'GET',
headers: {
Authorization: "Token "+$.cookie("token")
},
data:{'start':start,'end':end, 'grain': grain},
success:function (e) {
for(var i=0;i<e.length; i++){
x[i] = e[i].time;
y1[i] = e[i].tdevice_cnt;
y2[i] = e[i].enduser_cnt;
y3[i] = e[i].interact_times;
}
},
dataType: "JSON"
});
show();
}
其实这里犯了一个很大的错误,由于Ajax是异步的,所以如果把show()放在Ajax外面的话,相当于数据请求和填充数据是一块执行的,所以图表不会有数据。
正确代码:
function select() {
x.splice(0, x.length);
y1.splice(0, y1.length);
y2.splice(0, y2.length);
y3.splice(0, y3.length);
var start = $("#start").val();
var end = $("#end").val();
var grain = $("#grain").val();
$.ajaxSetup({
data:{csrfmiddlewaretoken:$("#hidden").val()}
});
$.ajax({
url:'xxx',
type:'GET',
headers: {
Authorization: "Token "+$.cookie("token")
},
data:{'start':start,'end':end, 'grain': grain},
success:function (e) {
for(var i=0;i<e.length; i++){
x[i] = e[i].time;
y1[i] = e[i].tdevice_cnt;
y2[i] = e[i].enduser_cnt;
y3[i] = e[i].interact_times;
}
show();
},
dataType: "JSON"
});
}