如何在Django模板中从JQuery脚本调用Python函数
我刚接触django和jquery,想找一个用django1.3做的“你好,世界”的示例。这个示例的意思是,当用户点击一个按钮或者加载页面时,服务器会返回一个字符串或json格式的“你好,世界”给客户端。
注意:我使用的是django1.3和python 2.7。抱歉,这个问题很基础。
我成功地用jquery显示了一个字符串“这是通过JQuery显示的你好,世界”,而且没有使用任何视图函数(只用jquery)。但我不知道怎么从jquery函数中调用视图函数。如果有人知道,请帮帮我。谢谢!我尝试了以下代码片段。
urls.py
(r'^hellofromserver/$',views.test),
def test(request):
if request.method == 'GET':
json = simplejson.dumps('hello world!')
return HttpResponse(json, mimetype = 'application/json')
jqueyhelloserver.html:
<html>
<head>
<title>jQuery Hello World</title>
<script type="text/javascript" src="{{STATIC_URL}}js/jquery-1.2.6.min.js"></script>
</head>
<body>
.....
<script type="text/javascript">
# how can I get'hello world' from test function(What is the sytax )
</script>
<div id="msgid">
</div>
</body>
</html>
我该如何从jquery调用' test '和' hellofromserver '这两个函数呢?(从模板中调用)。
2 个回答
0
...你遇到什么问题了?你的Javascript控制台有没有显示什么信息?可能是你还没有设置你的django应用来使用CSRF保护。
2
最后我从服务器收到了一个'hello'!
urls.py:
from django.views.generic.simple import direct_to_template
(r'^hello/$',direct_to_template, {'template': 'jqueryserver.html'}),
(r'^jqueryserver/$',views.jqueryserver),
views.py:
#other imports
from django.views.decorators.csrf import csrf_exempt
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_protect
def jqueryserver(request):
print "in jqueryserver"
response_string="hello"
if request.method == 'GET':
if request.is_ajax()== True:
return HttpResponse(response_string,mimetype='text/plain')
jqueryserver.html
<html>
<head>
<title>jQuery Hello World</title>
<script type="text/javascript" src="{{STATIC_URL}}js/jquery.js"></script>
<script>
$.ajax({
type: "GET",
url: "/jqueryserver/",
success: function(data){
alert(data);
}
});
</script>
</head>
<body>
<form method ="GET" >
<input type= "submit" id = "save" value ="Save" />
</form>
<div id= "test"></div>
</body>
</html>