javascript - 如何使用 AJAX 和 Flask 在 python 服务器和 javascript 客户端之间进行通信?
问题描述
我正在按照本教程在 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 文件中的按钮时,教程说我将能够在 Web 浏览器中看到服务器响应。但即使我的服务器正在运行,这也是我在 Firefox Web 浏览器中 index.html 的开发人员工具的网络选项卡中看到的内容:
我不明白我做错了什么以及我应该如何看到客户端和服务器之间的通信。任何帮助,将不胜感激
解决方案
您的请求未发送 JSON,您必须对汽车对象进行字符串化以将其作为 JSON 发送。
function doWork() {
console.log("posting data")
// ajax the JSON to the server
$.post("receiver", JSON.stringify(cars), function(){
}, 'application/json');
// stop link reloading the page
event.preventDefault();
}
我还将内容类型设置application/json
为request.get_json()
.
对于您的网络选项卡问题,您已JS
选择这样您就不会只看到 ajax 请求 javascript 文件。您必须XHR
选择 或All
。
推荐阅读
- node.js - IBM Watson Assistant:聊天机器人调用本地节点功能
- pytorch - Pytorch LSTM 与 LSTMCell
- java - 使用 JavaFX 和 Gluon,如何在单击按钮时从 loginPage 更改为 MainMenu?
- excel - VBA 受保护的单元格,但仍允许编辑
- android - Android webview:抛出一些令牌错误。google.android.gms。一些东西加上 webcookies 没有正确缓存
- postgresql - Azure ApplicationInsights 应用程序映射默认不显示 PostgreSql 依赖项
- konvajs - 如何检索剪辑区域的 dataURL?
- javascript - 同时使用两个滚动插件
- excel-formula - 如何使用 MAX 或 LARGE 函数检索现有 INDEX MATCH 公式中的最新日期条目?
- date - 在 Laravel 上为可为空的日期列设置自定义默认日期