2011-09-30 48 views
-1

我是新的django和jquery,我是searching for a 'hello world' sample for jquery使用django1.3,其中hello世界从服务器返回到客户端的字符串/ json当用户按下按钮时或者在加载页面时。如何从Django模板中的Jquery脚本调用python函数

注:我正在使用django1.3和python 2.7。这是一个非常基本的问题。

我成功地显示了一个字符串“这是JQuery的Hello World”没有任何视图函数(只使用jquery)。但我不知道如何使用jQuery函数的视图函数 如果有任何人有想法请在advance.om模板 帮助me.Thanks我尝试使用下面的代码片段。

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的 'hellofromserver'(从模板)?

+0

我只需要知道如何jQuery的通信服务器? – Jisson

回答

0

最后我从服务器得到了'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> 
+0

''post'include来自django projectinto脚本的代码https://docs.djangoproject.com/en/1.3/ref/contrib/csrf/#ajax – Jisson

0

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

+0

,谢谢你的回答。我的代码的其他部分可以吗? 。以下是从jquery调用python fn的方法。 1)$。getJSON(“http://127.0.0.1:8000/viewname?callback= 2)$。getJSON(”http://127.0.0.1:8000/url?callback= – Jisson

相关问题