Skip to content

Instantly share code, notes, and snippets.

@qguv
Last active October 6, 2017 02:16
Show Gist options
  • Save qguv/6bc132ce5fb5f2f86769d25da625f940 to your computer and use it in GitHub Desktop.
Save qguv/6bc132ce5fb5f2f86769d25da625f940 to your computer and use it in GitHub Desktop.
server communication without page refresh
from random import choice
from flask import Flask, render_template, jsonify
app = Flask(__name__)
@app.route('/page')
def page():
return render_template('page.html')
@app.route('/sensors')
def sensor():
animal = choice(['snake', 'octopus', 'lizard', 'cat'])
return jsonify({
'sensor1': animal
})
app.run(port=8888)
<html>
<head>
<script type="text/javascript">
function clicked() {
fetch('/sensors', {
method: 'GET',
headers: new Headers()
})
.then(data => data.json())
.then(json => {
const sensor_data = json['sensor1'];
const button = document.getElementById('clickme');
button.textContent = sensor_data;
});
}
</script>
</head>
<body>
<button id='clickme' onclick="clicked();">Click me</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment