Question on a jquery-ajax function, Using Django
I am new to Django, Ajax and HTML. I am currently developing a simple website for learning purposes.
The site fetches recent news from my db and displays the 5 latest news entry. This should be done without the user refreshing the whole page.
The code below may not seem much, but it is the the result of a painfully long learning process from my end.
Question comes at the end.
url.py
site_media = '/django/feed/site_media/'
urlpatterns = patterns('',
(r'^$', 'recent.views.recent_feed_view'),
# Site media
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': site_media}),)
models.py
class news(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateField('date published')
views.py
def recent_feed_view(request):
show_results = False
new_feed = []
if 'get_feed' in request.GET:
show_results = True
new_feed = news.objects.order_by('-pub_date')[:5]
variables = RequestContext(request, {
'new_feed': new_feed,
'show_results': show_results,})
if request.GET.has_key('ajax'):
return render_to_response('feed_list.html', variables)
else:
return render_to_response('recent_news.html', variables)
recent_news.html
<html>
<head>
<script type="text/javascript" src="/site_media/jquery.js"> </script>
<script type="text/javascript"src="/site_media/get_feed.js"></script>
</head>
<body>
<form id="search_feed_form" method="get">
<input name = "get_feed" type="submit" value="get_feed" />
</form>
<div id="get_feed_div">
{% if show_results %}
{% include "feed_list.html" 开发者_开发百科%}
{% endif %}
</div>
</body>
</html>
feed_list.html
<ol class="news">
{% for news in new_feed %}
{{ news.question }}
<br />
{% endfor %}
</ol>
get_feed.js
function get_feed_js() {
$('#get_feed_div').load('/?ajax&get_feed');
return false;}
$(document).ready(function () {
$('#search_feed_form').submit(get_feed_js);});
Questions:
1- How can I modify my javascript function so that the page automatically fetches the latest news feed, say every 1 min, without having to press the button?
2- Is there a way to fetch the latest news feed when the user navigates to my website tab? (i.e.: he was currently viewing another tab on his browser and just clicked on the tab with my site on it)
I would greatly appreciate it if I could receive some tips / links to useful materiel that can help me move forward in this endeavor!
Use setInterval
: http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
setInterval('get_feed_js()', 60000); // call func every 60 seconds
$(window).one('focus', function() { // without one, I infinitely get focus event
get_feed_js(); // call function on tab focus
})
精彩评论