我想设置一种简单的方法,让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。
对于如何解决这个问题,我会很感激。
发布于 2017-07-24 21:32:51
请看这个答案:How to get POSTed json in Flask?
问题来自jQuery post请求:默认的mimetype是"application/x-www-form-urlencoded“当使用$.post时,请尝试使用带有contentType "application/json”的$.ajax,否则Flask将无法知道您发送的数据是JSON,并且在您调用get_json()时将返回None。
另一个想法是使用data而不是get_json(),然后解析结果:
data = request.data
dataDict = json.loads(data)https://stackoverflow.com/questions/45277660
复制相似问题