Reputation: 9893
As described in how to update a Django page without a page reload?, I send periodic XMLHTTPRequests from the browser to the server using JavaScript to get those pieces of the webpage that changes during the course of my application.
However, most of the time, nothing changes; the server replies with the same response and the browser updates the webpage with contents that's already been there.
Obviously, the server should only reply if there is new data.
A thorough web research came up with http://ajaxpatterns.org/Periodic_Refresh#Lace, but dcoumentation is terse and I'm struggling to implement the concept in my Django project. I have a hard time believing this has not been done before.
Does anyone know any further resources I could use as guideline ?
Upvotes: 2
Views: 5002
Reputation: 19495
The difficulty in answering is in not knowing what the server-side resources are that are being returned to the user.
I'll make up something which may serve as an example. Let's say you were developing an application that allowed you to monitor in real-time comments being made by users on your site. We can do several things to make this possible:
models.py
class Comment(models.Model):
text = models.TextField()
created = models.DateTimeField(default=datetime.now())
urls.py
url(r'^comments/latest/(?P<seconds_old>\d+)/$',get_latest_comments),
views.py
def get_latest_comments(request, seconds_old):
"""
Returns comments that have been created since the last given number of seconds
have elapsed.
"""
# Query comments since the past X seconds
comments_since = datetime.datetime.now() - datetime.timedelta(seconds=seconds_old)
comments = Comments.objects.filter(created__gte=comments_since)
# Return serialized data or whatever you're doing with it
return HttpResponse(simplejson.dumps(comments),mimetype='application/json')
On the client-side you get the JSON, check if it has a value, if so enumerate the items, and add the new items to your <div>
tag or whatever.
As you can see, the development of the API to return only recently updated items is going to vary based on what content the server is returning.
From your question it sounds like you want the server to manage identifying what is recently updated, not the client (which is a good strategy). In that case, what you need to do is define:
Upvotes: 9