[Fixed]-Pass JSON to JS using Django render

23👍

simplest way will be

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

Security warning.
json.dumps does not escape forward slashes: an attack is {'</script><script>alert(123);</script>': ''}

4👍

The trick is to convert your dict into a string for django 1.5+ do :

import json

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

In imageView/index.html keep:

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

Else do:

from django.utils import simplejson

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

In imageView/index.html keep:

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

1👍

You should pass the Django {{data}} to a raw JS String in order to prevent JS encoding/decoding problems.

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

Leave a comment