如何成功传递一个 Json 来渲染和操作它?



我正在尝试从 POST 请求返回 Json 响应,但我在路径中遇到了各种错误。

首先,我有以下看法

class ChartData8(APIView):
def tickets_per_day_results(request):
if request.method == "POST":
template_name = 'personal_website/tickets_per_day_results.html'
year = request.POST.get('select_year', None)
week = request.POST.get('select_week', None)
....do stuff...
data = {"label_number_days": label_number_days,
"days_of_data": count_of_days}
return render(request,template_name,JsonResponse(data))

调用包含 Ajax 请求的模板tickets_per_day_results.html

$.ajax({
method: "POST",
url: endpoint,
dataType: 'json',
contentType: "application/json",
headers: {"X-CSRFToken": $.cookie("csrftoken")},
success: function(data){
console.log(data)
label_number_days = data.label_number_days
days_of_data = data.days_of_data
setChart()
},
error: function(jqXHR,error_data, errorThrown){
console.log("error on data")
console.log(error_data)
console.log(JSON.stringify(jqXHR))
console.log("AJAX error: " + error_data + ' : ' + errorThrown)
}

但是这种组合给我带来了context must be a dict rather than JsonResponse错误。

我尝试了各种替代方案:

备选方案1:我用了如下Response,而不是JsonResponse

class ChartData8(APIView):
def tickets_per_day_results(request):
if request.method == "POST":
template_name = 'personal_website/tickets_per_day_results.html'
year = request.POST.get('select_year', None)
week = request.POST.get('select_week', None)
....do stuff...
data = {"label_number_days": label_number_days,
"days_of_data": count_of_days}
return render(request,template_name,Response(data))

但这抛出了错误context must be a dict rather than Response.

备选方案2:我没有JsonResponseResponse,而是尝试将对象转换为如下所示的字典:

class ChartData8(APIView):
def tickets_per_day_results(request):
if request.method == "POST":
template_name = 'personal_website/tickets_per_day_results.html'
year = request.POST.get('select_year', None)
week = request.POST.get('select_week', None)
....do stuff...
data = {"label_number_days": label_number_days,
"days_of_data": count_of_days}
return render(request,template_name, dict(Response(data)))

但这抛出了错误The response content must be rendered before it can be iterated over.

备选方案 3:我尝试在没有JsonResponseResponse的情况下传递数据,而不是 1 和 2:

class ChartData8(APIView):
def tickets_per_day_results(request):
if request.method == "POST":
template_name = 'personal_website/tickets_per_day_results.html'
year = request.POST.get('select_year', None)
week = request.POST.get('select_week', None)
....do stuff...
data = {"label_number_days": label_number_days,
"days_of_data": count_of_days}
return render(request,template_name, data)

但这抛出了 Ajax 请求中的错误parsererror,因为这意味着您只需返回一个字符串或其他值,它并不是真正的Json,因此解析器在解析它时失败。您可以通过从 Ajax 请求中删除dataType:'json'来避免此错误(解析器错误 Ajax 的解决方案(,但这不允许我从模板tickets_per_day_results操作我的数据集,也就是说,

删除dataType:json

$.ajax({
method: "POST",
url: endpoint,
headers: {"X-CSRFToken": $.cookie("csrftoken")},
success: function(data){
console.log(data)
label_number_days = data.label_number_days
days_of_data = data.days_of_data
setChart()
},
error: function(jqXHR,error_data, errorThrown){
console.log("error on data")
console.log(error_data)
console.log(JSON.stringify(jqXHR))
console.log("AJAX error: " + error_data + ' : ' + errorThrown)
}

那么我就无法操作在 Ajax 请求下方找到的数据集:

data: {
labels: label_number_days,
datasets :
[{
label: 'User_001',
data [days_of_data[0],days_of_data[1],days_of_data[2],days_of_data[3],days_of_data[4],days_of_data[5],days_of_data[6]],
backgroundColor: 'rgba(255, 99, 132, 0.6)',
borderColor: '#777',
borderWidth: 1,
hoverBorderWidth: 3,
hoverBorderColor: '#000'
},

因为你找到了Uncaught TypeError: Cannot read property '0' of undefined.

这是一条乏味的道路,我的想法(和耐心(已经用完了。如果有人能向我推荐任何其他选择,那么这将给我一些健康缓解。

更新每日门票结果 html 文件

{% extends "personal_website/header.html"%}
<script>
{% block jquery %}
var endpoint = '/tickets_per_day_results/' //This works with the chart_data view.
var days_of_data = []
var label_number_days = []
$.ajax({
method: "POST",
url: endpoint,
dataType: 'json',
contentType: "application/json",
headers: {"X-CSRFToken": $.cookie("csrftoken")},
success: function(data){
console.log(data)
label_number_days = data.label_number_days
days_of_data = data.days_of_data
setChart()
},
error: function(jqXHR,error_data, errorThrown){
console.log("error on data")
console.log(error_data)
console.log(JSON.stringify(jqXHR))
console.log("AJAX error: " + error_data + ' : ' + errorThrown)
}
})
function setChart()
{var ctx_tickets_per_day       = document.getElementById("tickets_per_day")
var tickets_per_day = new Chart(ctx_tickets_per_day, {
showTooltips: false,
type:'bar',
data: {
labels: label_number_days,
datasets :
[{
label: 'Oscar Gil',
data: [days_of_data[0],days_of_data[1],days_of_data[2],days_of_data[3],days_of_data[4],days_of_data[5],days_of_data[6]],
backgroundColor: 'rgba(255, 99, 132, 0.6)',
borderColor: '#777',
borderWidth: 1,
hoverBorderWidth: 3,
hoverBorderColor: '#000'
},
{
label: 'Oscar Rodriguez',
data: [days_of_data[7],days_of_data[8],days_of_data[9],days_of_data[10],days_of_data[11],days_of_data[12],days_of_data[13]],
backgroundColor: 'rgba(54, 162, 235, 0.6)',
borderColor: '#777',
borderWidth: 1,
hoverBorderWidth: 3,
hoverBorderColor: '#000'
},
{
label: 'Animesh Rathore',
data: [days_of_data[14],days_of_data[15],days_of_data[16],days_of_data[17],days_of_data[18],days_of_data[19],days_of_data[20]],
backgroundColor: 'rgba(255, 206, 86, 0.6)',
borderColor: '#777',
borderWidth: 1,
hoverBorderWidth: 3,
hoverBorderColor: '#000'
},
{
label: 'Bhaskar Sharma',
data: [days_of_data[21],days_of_data[22],days_of_data[23],days_of_data[24],days_of_data[25],days_of_data[26],days_of_data[27]],
backgroundColor: 'rgba(75, 192, 192, 0.6)',
borderColor: '#777',
borderWidth: 1,
hoverBorderWidth: 3,
hoverBorderColor: '#000'
},
{
label: 'Victor Catacora',
data: [days_of_data[28],days_of_data[29],days_of_data[30],days_of_data[31],days_of_data[32],days_of_data[33],days_of_data[34]],
backgroundColor: 'rgba(153, 102, 255, 0.6)',
borderColor: '#777',
borderWidth: 1,
hoverBorderWidth: 3,
hoverBorderColor: '#000'
},
{
label: 'Jimmy Gonzalez',
data: [days_of_data[35],days_of_data[36],days_of_data[37],days_of_data[38],days_of_data[39],days_of_data[40],days_of_data[41]],
backgroundColor: 'rgba(236, 115, 9, 1)',
borderColor: '#777',
borderWidth: 1,
hoverBorderWidth: 3,
hoverBorderColor: '#000'
},
{
label: 'Piyush Gupta',
data: [days_of_data[42],days_of_data[43],days_of_data[44],days_of_data[45],days_of_data[46],days_of_data[47],days_of_data[48]],
backgroundColor: 'rgba(185, 29, 12, 0.6)',
borderColor: '#777',
borderWidth: 1,
hoverBorderWidth: 3,
hoverBorderColor: '#000'
},
{
label: 'Carlos Prieto',
data: [days_of_data[49],days_of_data[50],days_of_data[51],days_of_data[52],days_of_data[53],days_of_data[54],days_of_data[55]],
backgroundColor: 'rgba(105, 129, 64, 0.6)',
borderColor: '#777',
borderWidth: 1,
hoverBorderWidth: 3,
hoverBorderColor: '#000'
},
{
label: 'Daniel Estrada',
data: [days_of_data[56],days_of_data[57],days_of_data[58],days_of_data[59],days_of_data[60],days_of_data[61],days_of_data[62]],
backgroundColor: 'rgba(15,  199, 84, 0.6)',
borderColor: '#777',
borderWidth: 1,
hoverBorderWidth: 3,
hoverBorderColor: '#000'
},
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
title: {
display: true,
text: 'Tickets by engineer per day',
fontSize: 30
},
legend: {
position: 'right',
display: true,
labels: {
fontColor: '#000'
}
},
layout: {
padding: {
left: 50,
right: 0,
bottom: 0,
top: 0
}
},
tooltips: {
enabled: true
},
hover : {
animationDuration: 0
},
animation: {
duration: 0.8,
onComplete: function(){
var chartInstance = this.chart,
ctx = chartInstance.ctx;
Chart.defaults.global.defaultFontColor = '#777';
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize,
Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset, i) {
var isHidden = dataset._meta[0].hidden; //'hidden' property of dataset
if (!isHidden) { //if dataset is not hidden
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y - 5);});
}});
}
}
}
})
}
{% endblock %}

{% block content %}
<div class ='row'>
{% csrf_token %}
<div class="col-sm-12" url-endpoint='{% url "tickets_per_day_results" %}'>
<div>
<canvas id="tickets_per_day" width="800" height="500"></canvas>
</div>
</div>
</div>
{% endblock content %}

我认为您使用了错误的方法以 JSON 格式返回数据。 在代码中:

render(request,template_name,JsonResponse(data))

在 Django 的文档中。呈现快捷方式用于呈现包含字典数据的 Html 模板以更新页面。

根据 django 代码,我猜你使用 Django rest Framework。 为了发送 JSON 数据,您应该使用此处的示例 DRF 示例响应,以便将 JSON 数据发送到页面。

最新更新