[英]Django passing JSON data to static getJSON/Javascript
I am trying to grab data from my models.py and serialize it into a JSON object within my views.py.我正在尝试从我的 models.py 中获取数据并将其序列化为我的 views.py 中的 JSON 对象。
Models.py:模型.py:
class Platform(models.Model):
platformtype = models.CharField(max_length=25)
Views.py:视图.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')
After doing this I want to pass this object into my static javascript file which is using getJSON to populate my drop down list for my template(Main.html).完成此操作后,我想将此对象传递到我的静态 javascript 文件中,该文件使用 getJSON 来填充我的模板 (Main.html) 的下拉列表。
JavaScript: JavaScript:
$.getJSON("{{platforms_as_json}}", function (data) {
$.each(data, function (index, item) {
$('#platformList').append(
$('<option></option>').val(item).html(item.platformtype)
);
});
});
I have looked at many other threads within SO, but all of them are for those using embedded JS within their template and/or not using getJSON.我已经查看了 SO 中的许多其他线程,但所有这些线程都是针对那些在其模板中使用嵌入式 JS 和/或不使用 getJSON 的。 As of right now, data is not being displayed in the list when I run my Django development server.
截至目前,当我运行 Django 开发服务器时,列表中未显示数据。 What am I doing wrong?
我做错了什么? Thank you.
谢谢。
UPDATE:更新:
<!DOCTYPE html>
<html>
<head>
{% load static from staticfiles %}
<script type = 'text/javascript' >
var platformsjson = "({% autoescape off %}{{platforms_as_json}}{% endautoescape %})";
</script>
</head>
<body>
<select id = "platformList"></select>
<ul id = "root"></ul>
<div id = "root"></div>
<script src = "{% static 'admin/js/platformddown_script.js' %}"></script>
</body>
</html>
platformddown_script.js: platformddown_script.js:
$.each(platformsjson, function (index, item) {
$('#platformList').append(
$('<option></option>').val(item.platformtype).html(item.platformtype)
)
});
After this update it still doesn't work.这次更新后还是不行。
Main html render + json data主 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)),})
in template在模板中
{{ platforms_as_json }}
html and js html 和 js
<select id="platformList"></select>
<script>
$.each({% autoescape off %}{{platforms_as_json}}{% endautoescape %}, function (index, item) {
$('#platformList').append(
$('<option></option>').val(item.platformtype).html(item.platformtype)
)
});
</script>
Old examplehttps://gist.github.com/leotop/014a38bd97407a6380f2526f11d17977旧示例https://gist.github.com/leotop/014a38bd97407a6380f2526f11d17977
我还遇到了一个视频资源,这里有力地解释了 JSONP 的工作原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.