Django将JSON数据传递给静态getJSON / Javascript
我试图从我的models.py中获取数据并将其序列化为我的views.py中的JSON对象。
Models.py:
class Platform(models.Model): platformtype = models.CharField(max_length=25)
Views.py:
def startpage(request): return render_to_response('Main.html'); def index(request): platforms_as_json = serializers.serialize('json', Platform.objects.all()) return HttpResponse(platforms_as_json, content_type='json')
执行此操作后,我想将此对象传递到我的静态javascript文件中,该文件使用getJSON填充我的模板(Main.html)的下拉列表。
JavaScript的:
$.getJSON("{{platforms_as_json}}", function (data) { $.each(data, function (index, item) { $('#platformList').append( $('').val(item).html(item.platformtype) ); }); });
我已经查看了SO中的许多其他线程,但所有这些线程都适用于在模板中使用嵌入式JS和/或不使用getJSON的线程。 目前,当我运行我的Django开发服务器时,数据没有显示在列表中。 我究竟做错了什么? 谢谢。
更新:
{% load static from staticfiles %} var platformsjson = "({% autoescape off %}{{platforms_as_json}}{% endautoescape %})";
platformddown_script.js:
$.each(platformsjson, function (index, item) { $('#platformList').append( $('').val(item.platformtype).html(item.platformtype) ) });
此更新后,它仍然无法正常工作。
主html渲染+ json数据
import json from django.shortcuts import render def startpage(request): platforms = Platform.objects.select_related().values('platformtype') return render(request, 'Main.html', {'platforms_as_json': json.dumps(list(platforms)),})
在模板中
{{ platforms_as_json }}
html和js
旧例子https://gist.github.com/leotop/014a38bd97407a6380f2526f11d17977