所以我想使用flask将数组发送到python脚本。
这是我相关的javascript:
var blacklist = [1];
function getSents() {
$.ajax({
type: "POST",
url: "script.py",
data: {'blacklist':blacklist},
dataType: 'json',
success: function(response) {
// do something
},
error: function (xhr, status, error) {
console.log(error);
}
});
}
在烧瓶中,我尝试了发现的每个请求属性。打印时,它始终会提供一个空字节字符串。
如果我使用
json.loads(request.data)
由于request.data为空,因此会引发错误。
相关的python代码:
from flask import Flask
from flask import render_template
from flask import request
from flask import jsonify
application = Flask(__name__)
@application.route('/', methods=['GET', 'POST'])
def something():
blacklist = request.get_data()
# do something
if __name__ == '__main__':
application.run(debug=True)
答案 0 :(得分:0)
尝试将contentType设置为'application / json'并对数据属性进行字符串化。然后在烧瓶中检查request.json
var blacklist = [1];
function getSents() {
$.ajax({
type: "POST",
url: "script.py",
data: JSON.stringify({'blacklist':blacklist}),
contentType: "application/json",
dataType: 'json',
success: function(response) {
// do something
},
error: function (xhr, status, error) {
console.log(error);
}
});
}
如果您正在寻找一个以此为起点的起点,那么应该可以
在app.py下
from flask import Flask
from flask import render_template
from flask import request
from flask import jsonify
application = Flask(__name__, static_url_path='/static')
@application.route('/', methods=['GET', 'POST'])
def something():
if request.method == 'GET':
return application.send_static_file('index.html')
blacklist = request.json
print(blacklist)
return jsonify(blacklist)
if __name__ == '__main__':
application.run(debug=True)
然后在/static/index.html
下<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<script>
var blacklist = [1];
function getSents() {
$.ajax({
type: "POST",
url: "script.py",
data: JSON.stringify({'blacklist':blacklist}),
contentType: "application/json",
dataType: 'json',
success: function(response) {
// do something
console.log(response)
},
error: function (xhr, status, error) {
console.log(error);
}
});
}
getSents();
</script>
</body>
</html>