我使用 django 的内置方法序列化了我的一个对象,然后将其传递到我的模板中。当我将 {{goals}} 放入 html 时,数据显示完美。但是,当我尝试通过 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))
蟒蛇模型
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)
JS文件
$("body").onload = load_goals();
function load_goals (){
alert(goals);}
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>
我尝试删除引号,现在当我执行 alert(goals) 时变量只是提醒 [object Object],[object Object]