在Django中使用dajax

I'm posting this question not because I am getting some errors but because I would like to know how dajax should be used

Here is what I want to do:

I want some links on my homepage (eg. books, authors), when user clicks them, he gets a list of books/authors.

Here is what I'm doing:

When user clicks on books, I call a dajax process. Inside ajax.py:

  • I get all the books using books = Book.objects.all()
  • I have a template = "{% for book in books %}"... blah blah blah
  • I render the template a = Template(template).render(Context(locals()))
  • I do dajax assign a as innerhtml of some div tag.

Is this the right way to do things? Instead of writing the template in ajax.py should I open templates from some xyz.html and then render it? Any other good, clean ways to get similar tasks done?

I never heard about dajax before (but it looks like the project has gone sightly inactive as the latest commit is ~10 months old), so I'll offer advice that is not directly related to dajax.

Basically, what you need to do is to display a list that is retrieved using AJAX. That's pretty trivial using the following tools:

  • jQuery (or another JS framework)
  • JSON

What you need to do is:

  1. Configure one of your views so that it returns a list of books (look here for the documentation)
  2. Access this view using your JS framewok of choice (jQuery.get() for jQUery)
  3. Using your JS framework, update some <ul> or <ol> on your page by adding the content that you retrieved through your get call (And you could place it in some overlay that you'd display).

Loading a template from a dedicated template file is in almost any case cleaner. A long python string with HTML in it is not very readable.

Of course you could also send your books via add_data(data,callback_function) and write a javascript callback function that populates the list which would be the Dajax way of doing what Thomas Orozco proposed.

But judging from the pagination example rendering a template file and sending it to innerHTML is 'the right way'.