这是我第一次使用AJAX,所以我试图制作网络使用情况监控器。我想绘制一个动态变化的图形。我正在使用谷歌图表和Django。
以下是我在JavaScript中的内容
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(repeat);
function repeat(){
$.ajax({
url: "http://127.0.0.1:8000/net/refresh/",
dataType:"json",
type:"GET",
success: function(data) {
var djangoData = {{data|safe}}
drawChart(djangoData)
}
});
setTimeout(repeat,3000);
}
function get_gchart_data(data)
{
var g_data = new google.visualization.arrayToDataTable(data);
return g_data;
}
function drawChart(djangoData) {
var g_data = get_gchart_data(djangoData);
console.log('hello')
// Instantiate and draw our chart, passing in some options.
var chart = new
google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(g_data, {width: 1000, height: 240, title: "Net usage"});
}
我检索所需数据数组的视图如下
def new(request):
a = [-25,-20,-15,-10,-5,0,5]
alpha = []
c = ['Time','Usage']
alpha.append(c)
i=0
for i in range(0,7):
c=[a[i],randint(0,50)]
alpha.append(c)
data = {'data':alpha}
if request.is_ajax():
print(alpha)
try:
print('hello')
return HttpResponse(json.dumps(data),content_type='application/json')
except:
return render(request,'netusage/working.html',data)
# return HttpResponse(simplejson.dumps(data), mimetype='application/json')
else:
raise Http404
在mapDraw中运行此console.log()时不会打印,这意味着不会调用成功。任何人都可以建议我哪里出错了。因为我不了解AJAX,所以直观的东西会很棒。