Django变量不被javascript识别

use*_*920 4 javascript django json

我使用django的内置方法序列化了我的一个对象,然后将其传递给我的模板.当我在html中放置{{goals}}时,数据显示完美.但是,当我尝试通过js脚本访问它时,它不起作用.为什么是这样?我提醒它,它一直未定.

#Python Views
def characterscreen(request):
    goals = serializers.serialize("json", Goal.objects.filter(userprofile=userprof)) 
    #goals = Goal.objects.filter(userprofile=userprof).values()
    return render_to_response('levelup/characterscreen.html', {'goals': goals}, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

Python模型

class Goal(models.Model):
    title = models.CharField(max_length = 30)
    userprofile = models.ForeignKey(UserProfile)
    type = models.CharField(max_length = 5)

    def __unicode__(self):
        return str(self.title)
Run Code Online (Sandbox Code Playgroud)

JS档案

    $("body").onload =  load_goals();


function load_goals (){
     alert(goals);}
Run Code Online (Sandbox Code Playgroud)

HTML

    <!DOCTYPE html>
    <html>
    <head>
        {% load staticfiles %}
        <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" type="text/css" href="{% static 'levelup/style.css' %}" />
        {% block header %}{% endblock%}
    </head>
    <body>
        <div id="headercontainer">
            <div id="header">

            </div>
        </div>
        {% block content %}{% endblock %}   <script type="text/Javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>  <script type="text/Javascript" src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script> 
<script type="text/javascript">goals = "{{ goals|safe }}"</script>
        <script type="text/Javascript" src="{% static 'levelup/script.js' %}"></script>
    </body>
    </html>
Run Code Online (Sandbox Code Playgroud)

我尝试删除引号,现在变量只是在我发出警报(目标)时警告[对象对象],[对象对象]

knb*_*nbk 5

这是因为外部.js文件不像html文件那样处理.这仅适用于内联脚本.所以你应该把它放在你的HTML文件中:

<script type="text/javascript">
    goals = "{{ goals }}"
</script>
<script type="text/javascript" src="script.js" />
Run Code Online (Sandbox Code Playgroud)

然后,您可以在script.js中使用目标变量.

编辑:
JSON总是使用双引号,所以你必须在它周围加上单引号.此外,通过JSON字符串实际表示在没有引号的情况下使用真正的Javascript对象时,最好在使用它之前解析JSON.当你似乎使用jquery时,使用:

goals = $.parseJSON('{{ goals|safe }}')
Run Code Online (Sandbox Code Playgroud)