[英]AJAX POST data does not show up in Python
我使用HTTP POST
请求jQuery
。
function getData() {
const data = JSON.stringify({
"test_id": "1"
});
jQuery.post('/getData', data, function (response) {
alert("success");
console.log(response)
}, "json");
}
当我在 Python 中收到请求时,当我尝试打印request.data
时,字符串为空。
当我附加调试器时,我看到数据在form
( request.form
)下。
如何使它们可以从request.data
访问?
提前致谢
您需要将参数作为{}
发送,以便您可以使用contentType
。
文件: jQuery.post
jQuery.post({
url: "/getData",
data: data,
success: function (response) {
alert("success");
console.log(response);
},
dataType: "json",
contentType: 'application/json'
});
使用contentType: 'application/json'
你应该把它作为request.data
和request.json
来获取,这可能更有用。
最少的工作代码
from flask import Flask, request, render_template_string, jsonify
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template_string('''
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
function getData() {
const data = JSON.stringify({"test_id": "1"});
jQuery.post({
url: "/getData",
data: data,
success: function (response) {
alert("success");
console.log(response);
},
dataType: "json",
contentType: 'application/json'
});
}
getData();
</script>
</head>
</html>
''')
@app.route('/getData', methods=['GET', 'POST'])
def get_data():
print('args :', request.args)
print('form :', request.form)
print('data :', request.data)
print('json :', request.json)
print('files:', request.files)
return jsonify(["Hello World"])
if __name__ == '__main__':
#app.debug = True
app.run()
结果:
args : ImmutableMultiDict([])
form : ImmutableMultiDict([])
data : b'{"test_id":"1"}'
json : {'test_id': '1'}
files: ImmutableMultiDict([])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.