Reputation: 183
I'm using setInterval()
function to reload information every 5 seconds. The html looks like:
<div id = "update"> </div>
<script>
window.setInterval(
function() {
$("#update").load("/game");
}, 5000);
</script>
In Flask, my views.py
:
@app.route('/game')
def live_game():
text = "<p> test </p>"
return text
Now, I'd like to change the variable text every time the page reloads. Something like:
counter = 0
@app.route('/game')
def live_game():
textlist = ['a','b','c','d']
text = "<p> "+textlist[counter]+" </p>"
counter += 1
return text
This obviously doesn't work, as I'm sure I need to be incrementing on the jQuery side, I'm just not sure how. Any help would be appreciated!
Upvotes: 0
Views: 1976
Reputation: 689
To make it work you need to modify your JavaScript as well as your views.py
, here are the modifications you should be doing
HTML
<div id = "update"> </div>
<script type="text/javascript">
var counter = 0;
window.setInterval(function(){
$("#update").load("/game?counter=" + counter);
counter++;
}, 5000)
views.py
from flask import request
@app.route("/game")
def live_game():
textlist = ['a','b','c','d']
counter = request.args.get('counter')
return "<p> " + textlist[counter] + " </p>"
The output will be
<div id = "update"><p> a </p></div>
// after 5 seconds
<div id = "update"><p> b </p></div>
// and so on
Let me know if you still face any issue.
Have fun :)
Upvotes: 1
Reputation: 14581
You need to call the /game
flask endpoint in your setInterval function. Here is much what you need.
<script>
window.setInterval(
function() {
$.ajax("/game", {dataType:'text', cache: false}).done(function(data){
$("#update").html(data);}
);
}, 5000);
</script>
The method will update with whatever the /game endpoint returns. It is unclear what you intend to be updating or incrementing.
Upvotes: 0