[英]How do you get an object from an array of JavaScript dicts by key?
[英]Pass array of dicts from python to Javascript
我無法訪問從python腳本傳遞到javascript的字典數組。 當我使用以下代碼時,沒有彈出警報消息。 我在這里做錯了什么?
errors = [1, 2]
graphs = [{'A': 1}, {'B': 2}]
return render(request, 'index.html', {'errors': errors, 'graphs': graphs})
# index.html
<script>
if ({{ graphs }}){
alert('Detected');
}
if ({{ errors }}){
alert('Detected');
}
</script>
我什至嘗試將其轉換為json,但仍然存在相同的問題。
mygraphs = json.dumps(graphs)
return render(request, 'index.html', {'errors': errors, 'graphs': mygraphs})
我可以在HTML內訪問數組。
{% for graph in graphs %}
<li style="color: red;">Element detected</li>
{% endfor %}
打印兩次Element detected
。 但是我無法在腳本中執行此操作。
Django模板將單引號替換為'
實體。 因此,將safe
過濾器添加到graphs
變量:
if ({{ graphs|safe }}){
alert('Detected');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.