I would like to setup a simple way of having javascript in a client web page to communicate with a python server. The final goal is to create a simple web-browser based game for 2-4 players which access some page, and where they can do something (and see some graphics generated by three.js
). Therefore, I would like to have the client in javascript, and the backend in python (because python is great).
My previous questions are here and here. Now I tried yet another example following this description but again it didn't work.
Here is the full code, index.html
:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
// setup some JSON to use
var cars = [
{ "make":"Porsche", "model":"911S" },
{ "make":"Mercedes-Benz", "model":"220SE" },
{ "make":"Jaguar","model": "Mark VII" }
];
window.onload = function() {
// setup the button click
document.getElementById("theButton").onclick = function() {
doWork();
};
};
function doWork() {
// ajax the JSON to the server
$.post("receiver", cars, function(){
});
// stop link reloading the page
event.preventDefault();
}
</script>
This will send data using AJAX to Python:<br /><br />
<a href="" id="theButton">Click Me</a>
</body>
</html>
and here is the python code:
import sys
from flask import Flask, render_template, request, redirect, Response
import random, json
app = Flask(__name__)
@app.route('/')
def output():
# serve index template
return render_template('index.html', name='Joe')
@app.route('/receiver', methods = ['POST'])
def worker():
# read json + reply
data = request.get_json() # HERE
print(data)
result = ''
for item in data:
# loop over every row
result += str(item['make']) + '\n'
return result
if __name__ == '__main__':
# run!
app.run()
The problem is that the data received in the python code (HERE) the data is None
.
I would appreciate ideas on how this can be fixed.