What's a good way to format AJAX responses? Or, using Django templating with AJAX

Posted by synic on Stack Overflow See other posts from Stack Overflow or by synic
Published on 2010-05-06T18:41:09Z Indexed on 2010/05/06 19:28 UTC
Read the original article Hit count: 138

Filed under:
|

In some of the code I'm working on, the author max AJAX calls to a Django view that returns JSON.

Once the JSON is retrieved, it'll be injected into the page with a function that looks like this (note, this is a simplification, but I'm sure you know what I'm getting at here):

function build_event_listing(events) {
    var html = '';

    for(int i = 0; i < events.length; i++) {
        event = events[i];

        html += "<h2>" + event.title + "</h2>\n";
        html += "<p>" + event.description + "</p>";
        html += "Click <a href='/event/view/" + event.id + "'>here<a> for more info.";

    }

    events_div.html(html);
}

I really don't like this approach. To change the look of each event listing, the designer would have to modify that ugly JS. I'd much rather make use of Django's templating system, but I'm wondering how I can do this?

I had the idea of writing the view like this:

def view_listings(req):
    events = models.Event.objects.all()

    html = []
    for event in events:
        html.append(
            render_to_string('event/single_event.html', {
                'event': event,
            }, context_instance=RequestContext(req))

    return HttpResponse(''.join(html), mimetype='text/html')

... but it just seems like there should be a better way.

Any ideas?

© Stack Overflow or respective owner

Related posts about django

Related posts about JavaScript