2012-06-12 44 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'