2012-06-12 43 views
1

我想发送一个ajax请求到我的views.py,但我不知道如何使用路径。 我的意见位于我的服务器上/home/pycode/main/main/apps/builder/views.py. 我发送请求的页面位于/home/dbs/www/python.html 我需要向我的urls.py添加内容吗?django简单的ajax请求

views.py

#!/usr/bin/env python26 
from django.http import HttpResponse 
def main(request): 
    return HttpResponse("from python with love") 

python.html jQuery的AJAX

<script language="JavaScript"> 
$(document).ready(function() { 
$("#myform").submit(function() { 

    var myCheckboxes = new Array(); 
    $("input:checked").each(function() { 
     myCheckboxes.push($(this).val()); 
    }); 
    $.ajax({ 
     type: "POST", 
     url: '/main', 
     data: { myCheckboxes:myCheckboxes }, 
     success: function(response){ 
      alert(response); 
     } 
    }); 
    return false; 
}); 
}); 
</script> 

回答

5

要永远通过他们的文件系统中的位置访问的观点,你在urls.py指他们通过他们的作品的功能。

阅读django教程(4页)将非常有帮助。

https://docs.djangoproject.com/en/dev/topics/http/urls/

在urls.py你使用类似的条目映射一个URL的功能:

urlpatterns = patterns('', 
    (r'^main/$', 'apps.builder.views.main'), 
) 

然后,每当你输入“/主/`作为一个URL它映射到你的观点功能。

+0

很好的回答。到OP:如果你在'/ main /'中包含一个斜线,确保将它添加到javascript中的url中,否则你可能会遇到问题。 – Alasdair

+0

但我的应用程序需要位于'/ home/dbs/www /'与我的网站,还是它只需要在服务器的某个地方? – user1442957

+0

@ user1442957你的应用程序可以位于任何地方。如果您使用的是开发服务器,当您向其发送请求时,您的应用程序将被初始化为默认端口:8000,因此任何请求'localhost:8000'都将进入您的应用程序 – dm03514

2

就服务器而言,Ajax请求就像任何其他请求一样。所以,是的,你需要的东西在urls.py。

0

而对于Ajax请求,您可以使用JSON响应:

# -*- coding: utf-8 -*- 

from django.http import HttpResponse 
from django.utils import simplejson 

class JsonResponse(HttpResponse): 
    """ JSON response 

    """ 
    def __init__(self, content, status=None, mimetype=None): 
     """ 
      @param content: string with json, or python dict or tuple 
      @param status: Http status 
      @param mimetype: response mimetype 
     """ 
     if not isinstance(content, basestring): 
      content = simplejson.dumps(content) 
     super(JsonResponse, self).__init__(
      content=content, 
      mimetype=mimetype or 'application/json', 
      status=status 
     ) 
     self['Cache-Control'] = 'no-cache' 
     self['Pragma'] = 'no-cache'