我试图将Javascript数组从客户端传递到服务器端(Flask)。我的代码似乎适用于整数和字符串。当我尝试使用完全相同的代码发送数组时,我得到了None
。
服务器端代码:
@app.route("/route1", methods=['GET', 'POST'])
def route1():
a = request.args.get('post')
result = json.dumps(a)
print(a)
print(result)
客户端:
$SCRIPT_ROOT = {{ request.script_root | tojson | safe }};
var x = ["test", "test2"];
function newFunction() {
console.log(x)
$.getJSON($SCRIPT_ROOT + '/route1', { post: x },
function (data) {
var response = data.result;
console.log(response);
}
)
};
就像我之前说过的,当x
简单地分配一个字符串或整数时,这似乎完美地工作了。当试图通过该数组时,我分别得到了None
和NULL
两个打印语句。如何正确地通过阵列传递到服务器端?
是的,我都无法使用$.getJSON
它来执行此操作...
这是一个经过测试的$.ajax
解决方案:
<script>
$SCRIPT_ROOT = {{ request.script_root | tojson | safe }};
var x = ["test", "test2"];
function f1(){
$.ajax({
type: "POST",
url: $SCRIPT_ROOT + "/route1",
contentType: "application/json",
dataType: "JSON",
data: JSON.stringify(x)
});
};
</script>
我用这样的按钮触发它:
<button id="testing" name="testing" onclick="f1();">testing</button>
和Flask代码:
@bp.route("/route1", methods=['GET', 'POST'])
def route1():
a = request.get_json()
print(a)
return "hello, world"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句