简体   繁体   中英

Passing a django variable to javascript

我想将django变量传递给javascript这样的字典,该字典像这样的{u'testvar1':u'1',u'testvar2':u'38',u'testvar3':u'160'}。我似乎无法找到相同的解决方案。我是django的新手,非常抱歉这个noobie问题。

First, the fact that you have strings beginning with u means you are using Python 2.7, which is not only an extremely old version of Python but also means you are using outdated versions of Django, as more recent versions only support Python 3. You should upgrade both immediately.

To answer your question though, you should use JSON for this.

return render(request, 'my_template.html', {'data': json.dumps(data)}

and in your template:

var data = JSON.parse("{{ data|safe }}")

You pass the variables via the context and then can use them in your script in the django template

def myview():
    ...
    return render(request, 'my_template.html', {'testvar1': testvar1}


<script>
    var testvar1 = {{ testvar1 }}
</script>
def foo_view(request, slug):
    context_data = {u'testvar1': u'1', u'testvar2': u'38', u'testvar3': u'160'}
    return render(request, 'foo_template.html', context_data)

#foo_template.html
<script type="text/javascript">
   var a = "{{testvar1}}";
</script>

First take that dictionary in Django template and set it to the value of one of the html elements like this:

<input type="hidden" id="dict" value="{{your dict}}">

Now take value of html element in javascript.

In java script:
<script>
var dict = document.getElementById("dict").value;

</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM