问题描述
我正在使用Django为一个项目创建一个基于Web的应用程序,我遇到了一个将数组从Django视图返回到模板的问题。
I'm using Django to create a web-based app for a project, and I'm running into issues returning an array from a Django view to a template.
该数组将由JavaScript(JQuery)脚本用于在页面中显示的图像上绘制框。因此,这个数组除了别的以外还有一些要绘制的框的坐标。
The array will be used by a JavaScript (JQuery) script for drawing boxes on an image shown in the page. Therefore, this array will have, among other things, coordinates for the boxes to be drawn.
这是Django视图中用于获取所需数据和序列化的代码它作为JSON:
This is the code in the Django view used to get the required data and serialize it as JSON:
def annotate(request, ...):
...
oldAnnotations = lastFrame.videoannotation_set.filter(ParentVideoLabel=label)
tags = serializers.serialize("json", oldAnnotations)
...
return render_to_response('vannotate.html', {'tags': tags, ...})
作为一种调试方式,使用 {{tags}}
在模板的HTML部分将其作为输出(对于长行而言):
As a way of debugging, using {{ tags }}
in the HTML portion of the template gives this as output (sorry for the long line):
[{"pk": 491, "model": "va.videoannotation", "fields": {"ParentVideoFile": 4, "ParentVideoFrame": 201, "ParentVideoLabel": 4, "top": 220, "height": 30, "width": 30, "ParentVideoSequence": 16, "left": 242}}, {"pk": 492, "model": "va.videoannotation", "fields": {"ParentVideoFile": 4, "ParentVideoFrame": 201, "ParentVideoLabel": 4, "top": 218, "height": 30, "width": 30, "ParentVideoSequence": 16, "left": 307}}]
我认为是JSON数组的正确格式。
which I assume is the correct format for a JSON array.
在模板中,我试图在模板的JavaScript部分中实际使用标签
变量,如下所示:
Later on in the template, I attempt to actually use the tags
variable in the JavaScript portion of the template, as follows:
{% if tags %}
var tagbs = {{ tags|safe }};
var tgs = JSON.parse(tagbs);
alert("done");
{% endif %}
如果我删除 var tgs = JSON.parse(tagbs);
行,然后警告框弹出,其余JavaScript按预期工作。我们希望能够遍历Django模型中的所有对象,并获取JavaScript中的字段值。
If I remove the var tgs = JSON.parse(tagbs);
line, then the alert box pops up fine, and the rest of the JavaScript works as expected. Leaving this line in breaks the script, however.
我不知道我在这里做错什么,有人可以指出正确的方法吗?
I'm not sure what I'm doing wrong here, could someone point out the right way to do this?
推荐答案
JSON源代码是。即数组的JSON表示是您需要定义数组的Javascript源代码。
JSON is Javascript source code. I.e. the JSON representation of an array is the Javascript source code you need to define the array.
所以之后:
var tagbs = {{ tags|safe }};
标签
是一个包含数据的JavaScript数组你要。没有必要调用JSON.parse(),因为Web浏览器已经将其解析为JavaScript源代码。
tagbs
is a JavaScript array containing the data you want. There's no need to call JSON.parse(), because the web browser already parsed it as JavaScript source code.
所以你应该可以做到
var tagbs = {{ tags|safe }};
alert(tagbs[0].fields.ParentVideoFile);
,应显示4。
这篇关于将JSON数组从Django视图返回到模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!