为什么在python服务器上收到JSON消息为None?
问题描述:
我是网络编程新手,我正在学习如何在Python服务器和JavaScript客户端之间发送消息。为什么在python服务器上收到JSON消息为None?
我找到了以下指南:http://www.makeuseof.com/tag/python-javascript-communicate-json/,它指导您如何使用烧瓶创建python服务器以及如何使用AJAX和JQuery向其发送请求。
服务器Python代码(从与修改引导):
#!flask/bin/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():
print("execute worker()")
# read json + reply
data = request.get_json()
print("data = "+str(data))
if data is None:
return "Recieved data as None"
result = ''
for item in data:
# loop over every row
result += str(item['make']) + '\n'
return result
if __name__ == '__main__':
# run!
app.run()
客户端侧(命名为从与修改引导 “的index.html”,也):
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
console.log("started script");
// 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()
};
console.log("executed window.onload successfully");
}
function doWork() {
// ajax the JSON to the server
$.post("receiver", cars, function(){
});
// stop link reloading the page
event.preventDefault();
console.log("executed doWork successfully");
}
console.log("ended script");
</script>
This will send data using AJAX to Python:<br /><br />
<a href="" id="theButton">Click Me</a>
</html>
当我在我的本地主机上上传index.html,它会向控制台输出除“执行成功”之外的所有消息,这很有道理。
但是,当我点击按钮(一个ID为“theButton”的元素),它刷新页面,并不打印该消息。另外,在服务器端,我得到了“data = None”,并且当我在开发人员工具的网络中的响应选项卡中检查响应时,有时会收到“收到的数据为无”,有时甚至没有。
任何人都可以帮助我理解这种行为吗?我一步步跟着这个指南,但我找不到我的错误。
答
编辑:原来的解决方案是错误的,你应该参考链接的问题,jQuery posting JSON。
附加背景:Flask不会抛出任何异常。您还可以使用“网络”选项卡检查Chrome 发送的(请参阅How can I debug a HTTP POST in Chrome?)。
嗨,谢谢你的回应。 我试图添加你所说的,但它仍然不起作用。当我检查网络选项卡(我使用Firefox)中的响应时,我收到“收到的数据为无”响应。你知道为什么吗?此外,有时我会得到一个绿色的地位,有时灰色,这似乎没有发生什么事或什么... – Yair
检查你** **之前,你收到。 –
由于您的问题已被标记为重复,请查看链接问题显示的内容。我不是jQuery的专家。 –