Hello, I'm currently learning javascript and working on a django project. I've been trying to pass a dictionary template variable to javascript but have encountered some difficulties.
In my views.py file, the code looks like this:
def index(request):
name={'bishal':509,'bishnu':510}
return render_to_response("test.html",Context({'name':simplejson.dumps(name)}))
The test.html file includes:
{% 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 %}
The test.js file contains:
$(function myfunction() {
document.getElementById('btn1').onclick=function(){
name=JSON.parse(name);
alert(name);
};
});
However, an error message is displayed:
[30/Jul/2013 02:50:51] "GET /visualize/static/js/test.js HTTP/1.1" 404 2732
I also tried a similar approach in 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>
This method worked perfectly. Any assistance with resolving the issue would be greatly appreciated. Thank you!