2013-07-30 28 views
1

我是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> 

它完美地工作。請幫忙!

回答

2

忽略所有的JavaScript。你問題的關鍵在於:

[30/Jul/2013 02:50:51] "GET /visualize/static/js/test.js HTTP/1.1" 404 2732 

404是'文件未找到'的HTTP代碼,這意味着你正在使用不正確的路徑來引用你的JavaScript文件。解決這個問題,你可能會發現你的解決方案是有效的 - 或者,如果沒有的話,至少會有不同的解決方案。

+2

我想補充到OP,你在做什麼被認爲是非常不好的做法,應避免使用盡可能多的! –

+0

@limelights如果你想補充說,作爲一個單獨的答案和改進建議,我很樂意爲upvote,以便原始提問者至少可以看到它。我懷疑他是在維護別人的代碼,並且可能無法自己改變它。 –

+1

不,它不應該是必要的,但謝謝:) –

0

@Adrian對錯誤信息是正確的,但我懷疑你所考慮的問題是由於在test.html文件中沒有引用{{name}}引起的。嘗試:

<script type="text/javascript"> 
    var name='{{name}}'; 
</script>