如何在Python中接收对象数组作为参数使用AJAX作为HTTP请求传递Flask?
问题描述:
我的AJAX调用看起来是这样的:如何在Python中接收对象数组作为参数使用AJAX作为HTTP请求传递Flask?
$.ajax({
url: "/doSomeCoolThingOnServer",
type: "POST",
async: false,
data: {
simple_string: "Variable sent from client side",
array_of_strings: ["John", "George"],
array_of_objects: [
{ city: "Shanghai", population: 1000 },
{ city: "Budapest", population: 2501 }
]
},
success: function(response) {
console.log("===== SUCCESS =====");
console.log(response);
},
error: function(response) {
console.log("===== ERROR =====");
console.log(response);
}
});
我想收到数组对象如Python的类型的字典的数组的,但我有空数组返回。
@app.route("/doSomeCoolThingOnServer", methods=['POST'])
def doSomeCoolThingOnServer():
simple_string = request.form['simple_string']
array_of_strings = request.form.getlist('array_of_strings[]')
array_of_objects = request.form.getlist('array_of_objects[]')
print(simple_string) #returns desired string
print(array_of_strings) # returns desired array
print(array_of_objects) # returns empty array
请指教如何在Python中接收对象数组作为参数Flask作为HTTP POST请求使用AJAX传递?
答
您可以使用JSON.stringify
序列化您的对象,然后在服务器上使用json.loads
反序列化。这有效地将您的对象数组作为字符串数组发送。
序列化AJAX调用:
array_of_objects: [
JSON.stringify({ city: "Shanghai", population: 1000 }),
JSON.stringify({ city: "Budapest", population: 2501 })
]
反序列化服务器上:
import json
array_of_objects = request.form.getlist('array_of_objects[]')
print([json.loads(s) for s in array_of_objects])
另一种选择是单独序列整个阵列,而不是每个数组元素。这将对象的数组作为单个字符串发送:
array_of_objects: JSON.stringify([
{ city: "Shanghai", population: 1000 },
{ city: "Budapest", population: 2501 }
])
import json
array_of_objects = request.form['array_of_objects']
print(json.loads(array_of_objects))