【问题标题】:Pass JSON to JS using Django render使用 Django 渲染将 JSON 传递给 JS
【发布时间】:2017-12-03 02:37:14
【问题描述】:

在我的views.py 文件中,我有以下字典:

data = {'pk': '1980.24', 'model': 'artworks.metaData', 'fields': {'medium': 'Oil on canvas ', 'description': 'missing', 'credit': 'Gift of Nicholas Wyeth, 1980 ', 'collection': 2, 'height': '21.7', 'culture': 'Missing value', 'depictedPeople': 'missing', 'creation_date': '1896 ', 'account': 'n/a', 'original_url': 'http://www.metmuseum.org/art/collection/search/10738?sortBy=Relevance&what=Canvas%7cOil+paintings&ao=on&ft=*&offset=0&rpp=100&pos=1', 'url': 'annotatie01.io.tudelft.nl/collections/Metropolitan/1980.24.jpg', 'title': 'Gooseberries ', 'object_number': '1980.24', 'width': '35.7', 'artist': 'Joseph Decker '}}

我希望能够在我的网页上使用/访问这本词典。

我的尝试:

我尝试使用 views.py 中的渲染发送数据,

def foo():
    context = {'data':data}
    return render(request, 'index.html', context=context)

访问它使用:

<script type="text/javascript">
    var received_data  = "{{data}}";
</script>

使用这个,数据传输了,但是是乱码:

"{&#39;pk&#39;: &#39;1980.24&#39;, &#39;model&#39;: &#39;artworks.metaData&#39;, &#39;fields&#39;: {&#39;medium&#39;: &#39;Oil on canvas &#39;, &#39;descripti...etc

我尝试使用 json.dumps(data)JSON.parse(received_data ) 但这引发了错误:

 Uncaught SyntaxError: Unexpected token & in JSON at position 1.

简而言之

如何使用 Django Render() 将 JSON 数据从 Py 发送到 JS?

【问题讨论】:

    标签: javascript python json django


    【解决方案1】:

    诀窍是将您的 dict 转换为 django 1.5+ 的字符串:

    import json
    
    def foo():
        js_data = json.dumps(data)
        render_template_to_response("imageView/index.html", {"data": js_data})
    

    imageView/index.html保持:

    <script type="text/javascript">
        var received_data = "{{data|safe}}";
        console.log(received_data);
    </script>
    

    否则:

    from django.utils import simplejson
    
    def foo():
        js_data = simplejson.dumps(data)
        render_template_to_response("imageView/index.html", {"data": js_data})
    

    imageView/index.html保持:

    <script type="text/javascript">
        var received_data = "{{data}}";
        console.log(received_data);
    </script>
    

    【讨论】:

    • 似乎 simplejson 在 Django V1.5 之后被移除了。应该添加我自己的版本号。
    【解决方案2】:

    最简单的方法是

    <script type="text/javascript">
        var received_data  = "{{ data|safe }}";
    </script>
    

    安全警告json.dumps 不会转义正斜杠:攻击是{'&lt;/script&gt;&lt;script&gt;alert(123);&lt;/script&gt;': ''}

    【讨论】:

    • |的作用是什么?操作员?一个名字就可以了,所以我寻找文档。
    • 它不是名字兄弟。尝试查找 django 模板过滤器,您会发现可以在管道符号后使用过滤器 |带变量
    • @Exprator 我添加了一个安全警告,因为这种方法不安全。 json.dumps 的转义规则不是 100% 匹配 javascript 中使用的规则。
    【解决方案3】:

    您应该将 Django {{data}} 传递给原始 JS 字符串,以防止 JS 编码/解码问题。

    <script type="text/javascript">
        let received_data  = String.raw`{{ data|safe }}`;
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      • 2018-09-27
      相关资源
      最近更新 更多