Call Python function (Flask) from JavaScript file (melonJS) game on Facebook -
i've looked through many topics on stackoverflow, github, google , many more... , found many different answers although no simple answer.
i'm writing facebook game in javascript (using melonjs engine). framework flask (python).
what trying do, have ability send info between python , js code no need refresh page (like database operations, email sending, etc.). want user see game, take options, play , game rest.
while have managed see below work:
app.py
def add(f,l,a): g.db.execute('insert persons (fname,lname,age) values (?, ?, ?)', [f,l,a]) g.db.commit() @app.route('/') def index(): cur = g.db.execute('select fname, lname, age persons order id desc') entries = [dict(fname=row[0], lname=row[1], age=row[2]) row in cur.fetchall()] homecoming render_template('app.html',entries=entries,addtodb=add)
app.html
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>the game</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <meta name="generator" content="geany 1.22" /> <script type="text/javascript" src="jquery-1.7.1.min.js"></script> <script type="text/javascript"> var adddb = '{{addtodb('anne','monk','12')}}'; </script> </head> <body> {{addtodb('allie','monk','78')}} <ul class=entries> {% entry in entries %} <li><h2>{{ entry.fname }} {{ entry.lname|safe }} </h2> age: {{ entry.age }}</li> {% else %} <li><em>unbelievable. no entries here far</em></li> {% endfor %} </ul> </body> </html>
and both {{addtodb}} work. wonder how send function file.js linked html (like jquery above), not set straight inside. "{{...}}" not work checked. suppose have find module python or utilize ajax maybe, except have no thought start.
the reply "ajax", simplified elaboration help point in right direction:
you need create kind of js event (clicking link, clicking button, event firing in game) trigger asynchronous (i.e. doesn't wait server's response) or synchronous (i.e. wait hear back) phone call flask endpoint on server (i.e. route set up) request. if you're creating new entry, that's post request. validate on server , save database.
if want page reflect happened result of server's behavior database, flask endpoint needs homecoming json response. since generated html , js that's on page, function in js needs bound event listener looking json response, parses json , executes whatever code set in function.
jquery's ajax functionality you. here illustration of jquery ajax post. doesn't matter illustration uses php; parse post in flask view , homecoming jsonify(data). see docs on flask.jsonify.
javascript python facebook flask
No comments:
Post a Comment