提问人:mekise 提问时间:7/15/2023 最后编辑:Peter Mortensenmekise 更新时间:7/15/2023 访问量:53
通过 Ajax POST 将按钮值从 HTML 发送到 Flask 时空数据
Empty data when sending a button value from HTML to Flask through Ajax POST
问:
我正在尝试通过 Ajax POST 将 HTML 中单击的按钮的值发送到 Flask 函数。
我花了几个小时试图找到 POST 到 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 -
request.form
ImmutableMultiDict([('search', '')])
我做错了什么?
答:
在 JavaScript 代码中,用于检索单击的按钮的值。但是,指的是当前文档,而不是单击的按钮本身。若要解决此问题,请更新事件处理程序以正确定位按钮元素。完成版本:$this.val()
$this
<!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 class="my-button" value="btn1">Button1</button>
<button class="my-button" value="btn2">Button2</button>
</div>
</body>
<script>
$(document).ready(function() {
$('.my-button').on('click', function(event) {
var value = $(this).val();
$.ajax({
type: 'POST',
url: '/process',
contentType: 'application/json',
data: JSON.stringify({'search': value}), // Convert to JSON string
success: function(response) {
console.log(response);
}
});
event.preventDefault();
});
});
</script>
</html>
在修改后的代码中,我将类添加到按钮中,以便更轻松地在 jQuery 中定位它们。然后,我更新了事件处理程序,用于选择按钮并将事件绑定到这些按钮。"my-button"
$'.my-button'
click
在 Flask 应用中,可以使用 访问从 HTML 页面发送的值。下面是更新后的 Flask 代码:request.form['search']
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route('/process', methods=['POST'])
def process():
value = request.form['search']
print(value)
return jsonify({'message': 'Success'})
if __name__ == "__main__":
app.run(port=5000, debug=True)
我还在响应中添加了jsonify,以将其转换为JSON格式。这是可选的,但在处理 AJAX 请求时最好发送 JSON 响应。JSON在处理数据时也经常使用。
它现在应该可以工作了。
评论
return render_template()
success
success: function(response){document.write(response);}
评论