【发布时间】:2019-09-05 02:09:30
【问题描述】:
我是 Django 新手,我使用 chart.js 来填充 HTML 图表。我想刷新图表而不加载 HTML 本身。
HTML 图表如下所示
上面HTML的URL对应的视图在下面
**Views.py**
from __future__ import unicode_literals
from django.shortcuts import render
from django.views.generic import TemplateView
# Create your views here.
def dashboard(request):
if request.is_ajax():
print "this is ajax request inside dashboard function"
pass_tc=29
failed_tc=25
inprogress_tc=25
data = {'data':[pass_tc, failed_tc, inprogress_tc]}
request.GET.get('data')
print JsonResponse(data)
return JsonResponse(data)
context = {'data':[500,100,50]}
template='dashboard.html'
return render(request,template,context)
]
在 HTML 中,我使用了 Chart.js 的 updateChart() 功能
<button class='btn btn-success' onclick="updateChart()">Refresh</button>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'bar',
// The data for our dataset
data: {
labels: ['Pass', 'Fail', 'Inprogress'],
datasets: [{
label: 'Results',
//backgroundColor: 'rgb(255, 99, 132)',
//borderColor: 'rgb(255, 99, 132)',
backgroundColor:[
'green','Brown','orange'],
data: [10, 10,15]
}]
},
// Configuration options go here
options: {},
});
function updateChart(){
$.get("/dashboard/",{data:response.JsonResponse(data)}, function(data, status)
{
//console.log(data)
chart.data.datasets[0].data={{data}};
chart.update();
}
)
};
在服务器端我可以看到下面的响应
this is ajax request inside dashboard function
Content-Type: application/json
{"data": [29, 25, 25]}
[15/Apr/2019 18:52:12] "GET /dashboard/ HTTP/1.1" 200 22
所以 Ajax 请求正在获取数据。但是,我的图表没有填充这些数据。
它使用 View.py 中定义的非 Ajax 数据,也显示在图中 即
{'data':[500,100,50]}
我在我的 Ajax 请求中做错了什么。
【问题讨论】:
标签: javascript jquery html django chart.js