Last active
October 6, 2017 02:16
-
-
Save qguv/6bc132ce5fb5f2f86769d25da625f940 to your computer and use it in GitHub Desktop.
server communication without page refresh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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