【发布时间】:2021-08-16 06:34:15
【问题描述】:
我正在关注this 教程在 python 和 javascript 之间进行通信。我是这方面的初学者,所以我不明白我到底做错了什么。
以下是我在 index.html 中的代码,它在单击按钮时向 python 服务器端发送 POST 请求:
<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() {
console.log("posting data")
// 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 />
<button type="button" id="theButton">Click Me!</button>
这是我在 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 = ['GET', 'POST'])
def worker():
print("got some data")
# read json + reply
data = request.get_json()
result = ''
for item in data:
# loop over every row
result += str(item['make']) + ''
return result
if __name__ == '__main__':
app.run()
所以,当我按下 index.html 文件中的按钮时,tutorial 表示我将能够在 Web 浏览器中看到服务器响应。但即使我的服务器正在运行,这也是我在 Firefox Web 浏览器中 index.html 的开发者工具的网络选项卡中看到的:
我不明白我做错了什么以及我应该如何查看客户端和服务器之间的通信。任何帮助将不胜感激
【问题讨论】:
标签: javascript python ajax flask server