【发布时间】:2017-07-25 20:32:27
【问题描述】:
我想设置一种在客户端网页中使用 javascript 与 python 服务器通信的简单方法。最终目标是为 2-4 名玩家创建一个简单的基于 Web 浏览器的游戏,这些玩家可以访问某个页面,并且他们可以在哪里做某事(并查看由 three.js 生成的一些图形)。因此,我希望客户端使用javascript,后端使用python(因为python很棒)。
我之前的问题是here 和here。现在我在this description 之后尝试了另一个示例,但它再次不起作用。
这是完整的代码,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>
这里是python代码:
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()
问题是python代码中接收到的数据(这里)数据是None。
我将不胜感激有关如何解决此问题的想法。
【问题讨论】:
-
查看此答案:stackoverflow.com/questions/20001229/… 您必须将请求的 mimetype 设置为 'application/json' 才能使 request.get_json() 工作。
-
解决方案建议使用我已经使用的方法
request.get_json()。否则,请提供关于如何修复我的代码的确切代码 sn-p。
标签: javascript jquery python ajax flask