如何在Django-temp中从Jquery脚本调用python函数

2024-09-28 22:25:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我是django和jquery的新手,我是searching for a 'hello world' sample for jquery使用django1.3,当用户按下按钮或加载页面时,hello world将作为string/json从服务器返回到客户端。在

注意:我使用的是django1.3和python2.7。在

我成功地显示了一个字符串“This is Hello World by JQuery”,没有任何视图函数(仅使用JQuery),但不知道如何从JQuery函数中使用视图函数 如果有人有主意请帮忙我。谢谢在前进.om模板 我尝试使用以下代码片段。在

在网址.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公司名称:

^{pr2}$

如何从jquery调用函数“test”和“hellofromserver”?(来自模板)。在


Tags: django函数test视图模板jsonhellofor
2条回答

……你有什么问题?你的Javascript控制台有什么信息吗?可能您还没有将django应用程序设置为使用CSRF protection。在

最后我得到了服务器的“你好”!在

urls.py:
from django.views.generic.simple import direct_to_template

(r'^hello/$',direct_to_template, {'template': 'jqueryserver.html'}),
(r'^jqueryserver/$',views.jqueryserver),

在视图.py公司名称:

^{pr2}$

在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>

相关问题 更多 >