简体   繁体   English

从Facebook上的JavaScript文件(melonJS)游戏中调用Python函数(Flask)

[英]Call Python function (Flask) from JavaScript file (melonJS) game on Facebook

I've looked through many topics on stackoverflow, github, Google and many more... and found many different answers although no simple answer. 我浏览了关于stackoverflow,github,Google等等的许多主题,找到了许多不同的答案,尽管没有简单的答案。

I'm writing a Facebook game in JavaScript (using melonJS engine). 我正在用JavaScript(使用melonJS引擎)编写Facebook游戏。 The framework is Flask (Python). 该框架是Flask(Python)。

What I am trying to do, is to have ability to send data between Python and JS code with no need to refresh the page (like database operations, email sending, etc.). 我正在尝试做的是能够在Python和JS代码之间发送数据,而无需刷新页面(例如数据库操作,电子邮件发送等)。 I want the user just to see the game, choose options, play and the game does the rest. 我希望用户只看游戏,选择选项,玩游戏,其余的由游戏完成。

While I have managed to see that something like below will work: 虽然我设法看到以下内容可以正常工作:

app.py app.py

def add(f,l,a):
    g.db.execute('insert into persons (fname,lname,age) values (?, ?, ?)',
            [f,l,a])
    g.db.commit()

@app.route('/')
def index():
    cur = g.db.execute('select fname, lname, age from persons order by id desc')
    entries = [dict(fname=row[0], lname=row[1], age=row[2]) for row in cur.fetchall()]
return render_template('app.html',entries=entries,addtodb=add)

app.html 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>
        {% for entry in entries %}
            <li><h2>{{ entry.fname }} {{ entry.lname|safe }} </h2> Age: {{ entry.age }}</li>
        {% else %}
            <li><em>Unbelievable. No entries here so far</em></li>
        {% endfor %}
</ul>
</body>

</html>

And both the {{addtodb}} will work. 并且{{addtodb}}都将起作用。 I just wonder how to send the function to file.js that will be only linked to the HTML (like jquery above), not put directly inside. 我只是想知道如何将函数发送到仅链接到HTML(如上面的jquery)而不直接放在HTML中的file.js。 The "{{...}}" will not work as I already checked. “ {{...}}”将无法使用,因为我已经检查过了。 I suppose I have to find some module to Python or use AJAX maybe, except I have no idea where to start. 我想我必须找到一些Python模块或使用AJAX,除了我不知道从哪里开始。

The answer is "AJAX", but hopefully some simplified elaboration will help point you in the right direction: 答案是“ AJAX”,但是希望一些简化的说明可以帮助您指出正确的方向:

You need to make some kind of JS event (clicking a link, clicking a button, an event firing in your game) trigger an asynchronous (ie doesn't wait for the server's response) or synchronous (ie wait to hear back) call to a Flask endpoint on the server (ie the route you set up) with a request. 您需要进行某种JS事件(单击链接,单击按钮,游戏中触发事件)来触发异步(即不等待服务器的响应)或同步(即等待回听)调用服务器上带有请求的Flask端点(即,您设置的路由)。 If you're creating a new entry, that's probably a POST request. 如果要创建新条目,则可能是POST请求。 Validate it on the server and save it to the database. 在服务器上验证它并将其保存到数据库。

If you also want the page to reflect anything that happened as a result of the server's behavior with the database, your Flask endpoint needs to return a JSON response. 如果您还希望页面反映由于服务器对数据库的行为而发生的任何事情,则Flask端点需要返回JSON响应。 Since you already generated the HTML and JS that's on the page, a function in the JS needs to be bound as an event listener so it is looking for that JSON response, then parses the JSON and executes whatever code you put in the function. 由于您已经生成了页面上的HTML和JS,因此需要将JS中的函数绑定为事件侦听器,以便它查找该JSON响应,然后解析JSON并执行您放入该函数中的任何代码。

JQuery's ajax functionality does that all for you. JQuery的ajax功能可以为您完成所有这些工作。 Here is an example of a jQuery AJAX POST . 这是jQuery AJAX POST的示例 It doesn't matter that the example uses PHP; 该示例使用PHP没关系; you parse the POST normally in your Flask view and return jsonify(data). 您通常在Flask视图中解析POST并返回jsonify(data)。 See docs on Flask.jsonify . 请参阅Flask.jsonify上的文档

You have to use AJAX. 您必须使用AJAX。 On the server side, you just need a URL that returns your data in JSON form. 在服务器端,您只需要一个以JSON形式返回数据的URL。 On the client side, I suggest you use jQuery for AJAX requests. 在客户端,我建议您将jQuery用于AJAX请求。 Just request the data from the server with jQuery and render the data into the DOM. 只需使用jQuery向服务器请求数据,然后将数据呈现到DOM中即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM