views:

42

answers:

1

I have a very simple test with jQuery and a django view:

HTML - Includes jQuery.js
JavaScript - $(document).ready( $.get("/index/" ); )

Django urls.py:

(r'^index/', index_view ),

Django views.py:

def index_view(request): if request.GET: return HttpResponse( "RECEIVED GET" )

Debugging in browser, the javascript gets called but the view never displays "RECEIVED GET".

+1  A: 

First, you want to anonymous function here, like this:

$(document).ready(function() {
  $.get("/index/"); 
});

Then, this only gets the response, it doesn't do anything with it, if you want to do something with the content, do it in the callback, like this:

$(document).ready(function() {
  $.get("/index/", function(response) {
    alert(response);
  }); 
});
Nick Craver
oh yup. That alert is called, but I wanted to do something with the content in the view, like change the context im rendering the template with... The view doesn't seem to catch that $.get("/index/" at all =/
JonoRR
@JonoRR - If you want to load the result into something, say a `<div id="content">` use `.load()`, like this: `$("#content").load("/index/");`, is that what you're after?
Nick Craver
I want to catch it with my django view - index_view(request) in this case.
JonoRR
@JonoRR - You'll get that...I'm very confused, your view will get the request...what do you want to do with the response?
Nick Craver
Maybe it will help if i describe my situation. I have a page that displays a list of posts, with a search box at the top. Currently when the search box is submitted, my view function (index_view in views.py) is called where I filter the list of posts depending on the search query and then pass this list as part of the Context when rendering my template. Where the jQuery comes in is now I want (on every keypress inside the search box) to send a new GET with the updated query so I can re-render my template with the newly filtered results without having a page refresh.
JonoRR
Try autocomplete. http://solutions.treypiepmeier.com/2009/12/10/using-jquery-autocomplete-with-django/
dannyroa