Reputation: 1402
I searched about this concept, but don't really understand how it works exactly. My backend is using webapp2 and GAE, and I want to refresh a page that pulls from my database.
There's other content on the page, and I only need to refresh the table contents specifically. I currently am using
<meta http-equiv="refresh" content="10">
to refresh the entire page every 10 seconds, but I need something that only refreshes part of the page. An explanation of any JS or JQuery additions would be great!
The part that I really don't understand is what I have to change on the backend to allow this kind of refreshing.
Upvotes: 0
Views: 227
Reputation: 881555
A simple HTML placeholder:
<div id="tablehere"></div>
The Jquery code for AJAX-polling every 10 seconds:
setInterval(function(){
$.ajax({ url: "http://yourapp.appspot.com/thetable",
success: function(data) {
maketable(data);
}
});
}, 10000);
JS to make and show a new table (there are a million alternatives here and I'm no JS expert, this is just one way):
maketable = function(data) {
var tabdiv = document.getElementById("tablehere");
var tabhead = '<table><thead><tr><th>Col1</th><th>Col2</th></tr></thead><tbody>';
for(var i=0,len=data.length; i<len; i++) {
tabhead += '<tr><td>' + data[i].col1 + '</td><td>' + data[i].col2 + '</td></tr>';
}
tabhead += '</tbody></table>';
tabdiv.innerHTML = tabhead ;
}
and that's it, clientside.
Server-side, app.yaml
will have a handler
url: /thetable
script: thetable.app
and in thetable.py
after all the needed imports:
class Tablerow(ndb.Model):
col1: ndb.StringProperty()
col2: ndb.StringProperty()
class Tablehandler(webapp2.RequestHandler):
def get(self):
data = [tr.to_dict() for tr in Tablerow.query().iter()]
response.write(json.dumps(data))
app = webapp2.WSGIApplication([('/thetable', Tablehandler)])
Phew -- very skeletal but still took me quite a while to write. But as you can see the app engine part is really trivial -- it's the HTML, Javascript, and Jquery side, that take by far the bulk of the effort!-)
Upvotes: 2