The problem in general is this: I have a page with content and user can comment it. Inserting comment should happen without reloading the page.
Commenting form gets handled in a view which saves the comment to database. After saving the comment I serialize the new comment to json and return to the page.
data = serializers.serialize('json', [comment])
return HttpResponse(data, mimetype='application/javascript')
This works quite well, comment gets prepended to the top of a div, but how do I apply formatting tags to jQuery? Comment is suppose to be displayed as
<div class="comment">{{comment}}<br>{{ comment.created | timesince }}</div>
Is it possible to apply template tags to jQuery-code? Of course there's a problem that 开发者_运维问答the other comments do not update, so the timesince is displayed wrong.. To correct this, I'd have to update whole comment list and loop all comments again to the page but the same problem still remains of course..
Is it possible to update whole listing of comments by somehow returning all comments as a dictionary and make jQuery load a template to display all comments..
Or any other idea how to solve this problem?
Instead of returning JSON, return HTML by rendering a template that contains the portion of the page you want to update. The client-side jQuery code can then insert the new HTML or replace existing HTML as needed.
The easiest thing to do would be to return the templated html from another view and use jquery's replaceWith.
精彩评论