簡體   English   中英

Django 將 JSON 數據傳遞給靜態 getJSON/Javascript

[英]Django passing JSON data to static getJSON/Javascript

我正在嘗試從我的 models.py 中獲取數據並將其序列化為我的 views.py 中的 JSON 對象。

模型.py:

class Platform(models.Model):
     platformtype = models.CharField(max_length=25)

視圖.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

我還遇到了一個視頻資源,這里有力地解釋了 JSONP 的工作原理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM