我是javascript新手。我正在研究django項目。我需要將字典模板變量傳遞給javascript,但我一直未能。字典傳給js不工作
views.py包括:
def index(request):
name={'bishal':509,'bishnu':510}
return render_to_response("test.html",Context({'name':simplejson.dumps(name)}))
的test.html包括:
{% load staticfiles %}
{% block include_js %}
<script src="{% static "js/chart.js" %}"></script>
<script src="{% static "js/test.js" %}"> </script>
{% endblock include_js %}
{% block main_content %}
<script type="text/javascript" src="static/js/test.js"></script>
<script type="text/javascript">
var name={{name}};
</script>
<button class="btn btn-primary" id="btn1" type="button" onclick="myfunction()">1st visualization</button>
{% endblock %}
test.js包括:
$(function myfunction() {
document.getElementById('btn1').onclick=function(){
name=JSON.parse(name);
alert(name);
};
});
但發生錯誤說:
[30/Jul/2013 02:50:51] "GET /visualize/static/js/test.js HTTP/1.1" 404 2732
我想類似的事情在HTML爲:
<html>
<head>
<script type="text/javascript">
function myfunction()
{
dict=JSON.parse(dict);
alert(dict);
}
</script>
</head>
<body>
<script type="text/javascript">
var dict='{"bishnu": 509, "bishal": 510}';
</script>
<form>
<input type="button"
onclick="myfunction()"
value="Call function">
</form>
<p>By pressing the button, a function will be called. The function will alert a message.</p>
</body>
</html>
它完美地工作。請幫忙!
我想補充到OP,你在做什麼被認爲是非常不好的做法,應避免使用盡可能多的! –
@limelights如果你想補充說,作爲一個單獨的答案和改進建議,我很樂意爲upvote,以便原始提問者至少可以看到它。我懷疑他是在維護別人的代碼,並且可能無法自己改變它。 –
不,它不應該是必要的,但謝謝:) –