Passing objects from Django to Javascript DOM

前端 未结 14 1151
野的像风
野的像风 2020-12-04 21:26

I\'m trying to pass a Query Set from Django to a template with javascript.

I\'ve tried different approaches to solve this:

1. Normal Approach - Javas

14条回答
  •  我在风中等你
    2020-12-04 22:14

    NOTE for django 2.1

    i found this a little confusing on django documentation so simply explaining a little bit easy way.

    we would normally use this like

    {{ my_info }}
    

    or loop over it depending on what we needed. But if we use the following filter,

    json_script 
    

    we can safely output this value as JSON

    {{ my_info|json_script:"my-info" }}
    

    Our data has been added as JSON, wrapped in a script tag, and we can see the data. We can now use this value by looking it up in JavaScript like so:

    info = JSON.parse(document.getElementById('my-info').textContent);
    

提交回复
热议问题