簡體   English   中英

將字典數組從python傳遞到Javascript

[英]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模板將單引號替換為&#39; 實體。 因此,將safe過濾器添加到graphs變量:

if ({{ graphs|safe }}){
    alert('Detected');
}

這應該工作

if("{{ graphs|safe }}"){
    alert('Detected');
}

請參閱此Django模板變量和Javascript

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM