0

我是 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 函数中的视图函数如果有人有想法请帮助我。谢谢Advance.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:

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

4

2 回答 2

2

最后我从服务器收到了一个“你好”!

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

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

视图.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>
于 2011-10-06T05:19:56.677 回答
0

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

于 2011-09-30T14:49:56.753 回答