Django ajax formatting convention
What's the correct way to do an ajax request, I've seen people using a returning render_to_string so that they can do all their formatting within python using the template language. eg~
return render_to_string('calendar.html', {
'self' : self,
'month' : self.today.month,})
with this as the javascript:
$('#django_calendar_response').html(response)
But I've also seen people formatting their output within javascript using dom functions such as
return HttpResponse(serializers.serialize("json",
ilst, relations=('user',)), "application/json")
where the javascript is
items_display=function(items){
return LI(null,
A({'class':'userlink',
'href':'/url/user/'+items.fields.user.fields.name},
items.fields.user.fields.name),
is one of these correct and the other wrong? sh开发者_开发技巧ould I format my output in javascript or within python?
I've been using JSON exclusively for AJAX, with simplejson returning whatever data is really easy, it looks like this:
from django.utils import simplejson
reply = simplejson.dumps({'comment_body': formatted_post, 'user_icon': request.user.profile.image.url })
return HttpResponse(reply, mimetype="application/json")
and on the client side, with jquery's .post method handling a json reply is really easy too, you can specify json as your datatype:
$.post("/postcomment/", { body: comment_body },
function(data){
alert(data.comment_body)
}, "json");
I'm not saying this is the best solution, but it's proven to be very robust and easy to handle...
Hope this helps,
Martin
I do both. Sometimes I have short template snippets that I {% include %}
in the big page template. It is often more DRY to render these and return the html to insert into the DOM (since the code is already set-up) than to have to write JS to do it (again). Other times, I just generate some JSON and inject that into the DOM.
Shortly, you can mix and match for the situation.
精彩评论