javascript - Django 将 JSON 数据传递给静态 getJSON/Javascript

标签 javascript jquery python mysql django

我正在尝试从我的 models.py 中获取数据并将其序列化为我的 views.py 中的 JSON 对象。

模型.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(
          $('<option></option>').val(item).html(item.platformtype)
);
 });
});

我看过 SO 中的许多其他线程,但它们都是针对那些在其模板中使用嵌入式 JS 和/或不使用 getJSON 的线程。截至目前,当我运行我的 Django 开发服务器时,数据没有显示在列表中。我究竟做错了什么?谢谢。

更新:

 <!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:

$.each(platformsjson, function (index, item) {
   $('#platformList').append(
           $('<option></option>').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

<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>

旧例子 https://gist.github.com/leotop/014a38bd97407a6380f2526f11d17977

关于javascript - Django 将 JSON 数据传递给静态 getJSON/Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38620816/

相关文章:

python - 替换字符串中的多个字符

python - 如何为具有多个可比较属性的对象实现 __hash__

python - 如何在 python 中正确构建 json web token

javascript - 使用 jQuery 和条件的表单输入

javascript - 你能根据分组数量获取 jQuery 中元素的子集吗?

javascript - 带有钩子(Hook)的 Socket.io 和 React 的奇怪行为

jQuery 在点击时隐藏 div 并显示另一个 div

javascript - 如何让 Bootstrap 弹出窗口与动态生成的图像链接一起使用?

javascript - 使用 Javascript/jQuery 对无序列表进行排序

jquery - 我的 getJSON 代码在 jquery 1.4.2 中不起作用