【发布时间】:2017-07-27 14:00:19
【问题描述】:
我是网络编程的新手,我正在尝试学习如何在 python 服务器和 JavaScript 客户端之间发送消息。
我找到了以下指南: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 时,它会将除“成功执行 doWork”之外的所有消息打印到控制台,这是有道理的。
但是,当我单击按钮(ID 为“theButton”的元素)时,它会刷新页面并且不会打印该消息。此外,在服务器端,我得到“data = None”,当我在开发者工具中检查网络响应选项卡中的响应时,有时我得到“Recieved data as None”,有时什么也没有。
谁能帮我理解这种行为?我一步一步地按照这个指南,但我找不到我的错误。
【问题讨论】:
标签: jquery python json ajax flask