user1442957
user1442957

Reputation: 7709

django simple ajax request

I am trying to send a ajax request to my views.py but I dont know how to use the path. My views is located on my server at /home/pycode/main/main/apps/builder/views.py. The page I am sending the request from is located at /home/dbs/www/python.html Do I need to add something to my urls.py?

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>

Upvotes: 1

Views: 2469

Answers (3)

Dingo
Dingo

Reputation: 2706

And for ajax request, you can use json response:

# -*- 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'

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599580

An Ajax request is just like any other request as far as the server is concerned. So, yes, you need something in urls.py.

Upvotes: 2

dm03514
dm03514

Reputation: 55962

To access functions in views you refer to them through their entries in urls.py never through their location in the filesystem.

Going through the django tutorial (4 pages) will help immensely.

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

in urls.py you map a url to a function using an entry similar to:

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

Then whenever you type '/main/` as a url it maps to your view function.

Upvotes: 5

Related Questions