【问题标题】:how call a python function from Jquery script in django template如何从 django 模板中的 Jquery 脚本调用 python 函数
【发布时间】:2011-11-28 09:21:53
【问题描述】:

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

注意:我使用的是 django1.3 和 python 2.7。对不起,这是一个非常基本的问题。

我成功地显示了一个字符串“This is Hello World by JQuery”,没有任何视图函数(仅使用 jquery)。但我不知道如何使用 jquery 函数中的视图函数 如果有人有想法请帮助我。在此先感谢.om 模板 我尝试使用以下代码 sn-ps。

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'?(来自模板)。

【问题讨论】:

  • 我只需要知道jquery如何与服务器通信?

标签: jquery python django django-templates django-1.3


【解决方案1】:

我终于得到了服务器的“你好”!

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>

【讨论】:

【解决方案2】:

...您遇到了什么问题?来自您的 Javascript 控制台的任何信息?也许你还没有设置你的 django 应用使用CSRF protection

【讨论】:

猜你喜欢
  • 2014-09-01
  • 1970-01-01
  • 2018-03-07
  • 2011-01-08
  • 2013-07-10
  • 2021-08-11
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
相关资源
最近更新 更多