我正在try 通过AJAX POST将在HTML中单击的按钮的值发送到Flask值函数.
我花了几个小时试图找到发布到Flask上的最小工作示例,但我没有找到任何真正最小的示例.这是我在多次堆栈溢出后创建的最小工作示例.这是我的HTML内容:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<div>
<button value="btn1">Button1</button>
<button value="btn2">Button2</button>
</div>
</body>
<script>
$(document).ready(function() {
$(this).on('click', function(event) {
var value = $(this).val();
$.ajax({
type : 'POST',
url : '/process',
contentType: 'application/json',
data : {'search' : value}
});
event.preventDefault();
});
});
</script>
</html>
这是我的FlASK应用程序:
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route('/process', methods=['GET', 'POST'])
def process():
value = request.get_json()
print(value)
return render_template('index.html')
if __name__ == "__main__":
app.run(port=5000, debug=True)
我使用print(value)作为调试判断.当我点击按钮时,我在终端收到一个错误400 127.0.0.1 - - [15/Jul/2023 03:04:49] "POST /process HTTP/1.1" 400 -
,但如果我try 使用request.form
,我得到一个空值,但正确的键ImmutableMultiDict([('search', '')])
我做错了什么?