JavaScript works asynchronously and after running send() it doesn't wait for response and it executes next line before it gets response with text.
To get one response you have to use xhr.onload
(before send()
) to define function which xhr
will run when it gets response
xhr.onload = function () {
latest.textContent = xhr.responseText;
}
xhr.send()
Minimal working code
from flask import Flask, render_template_string
import time
app = Flask(__name__)
@app.route('/')
def index():
return render_template_string('''<p>This is the current value: <span id="latest_value"></span></p>
<script>
var latest = document.getElementById('latest_value');
var xhr = new XMLHttpRequest();
xhr.open('GET', '{{ url_for('stream') }}');
xhr.onload = function() {
latest.textContent = xhr.responseText;
}
xhr.send();
/* this lines will give `><` because `xhr.responseText` is still empty */
/* you can remove these lines */
console.log(">" + xhr.responseText + "<")
latest.textContent = ">" + xhr.responseText + "<";
</script>''')
@app.route('/stream_time')
def stream():
def generate():
current_time = time.strftime("%H:%M:%S\n")
print(current_time)
yield current_time
return app.response_class(generate(), mimetype='text/plain')
app.run()
To update periodically text in browser you have to first use while
loop in generator to send many values.
For test I use also time.sleep(1)
to send less data
def generate():
while True:
current_time = time.strftime("%H:%M:%S\n")
print(current_time)
yield current_time
time.sleep(1)
Now in JavaScript you have to use xhr.onreadystatechange
to assign function which will update text on page when it gets new data from server
xhr.onreadystatechange = function() {
var all_messages = xhr.responseText.split('\n');
last_message = all_messages.length - 2
latest.textContent = all_messages[last_message]
}
Because xhr.responseText
ends with \n
so split('\n')
creates empty message as last element on list all_messages
so I use length - 2
instead of length - 1
Minimal working code
from flask import Flask, render_template_string
import time
app = Flask(__name__)
@app.route('/')
def index():
return render_template_string('''<p>This is the current value: <span id="latest_value"></span></p>
<script>
var latest = document.getElementById('latest_value');
var xhr = new XMLHttpRequest();
xhr.open('GET', '{{ url_for('stream') }}');
xhr.onreadystatechange = function() {
var all_lines = xhr.responseText.split('\\n');
last_line = all_lines.length - 2
latest.textContent = all_lines[last_line]
if (xhr.readyState == XMLHttpRequest.DONE) {
/*alert("The End of Stream");*/
latest.textContent = "The End of Stream"
}
}
xhr.send();
</script>''')
@app.route('/stream_time')
def stream():
def generate():
while True:
current_time = time.strftime("%H:%M:%S\n")
print(current_time)
yield current_time
time.sleep(1)
return app.response_class(generate(), mimetype='text/plain')
app.run()
BTW: because I used render_template_string(html)
instead of render_template(filename)
so I had to use \\n
instead of \n
http://your_domain.com/stream_time
send()
it may not wait for response and execute next line before it get response. You may have to usexhr.onload = function () {...}
to run code when it get response.\n
inxhr.responseText.split()
. To test code in JavaScript you can usealert()
orconsole.log(text)
(at least inFirefox
)