Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 如何在Python中接收对象数组作为参数,并使用AJAX作为HTTP请求传递?_Jquery_Python_Arrays_Ajax_Flask - Fatal编程技术网

Jquery 如何在Python中接收对象数组作为参数,并使用AJAX作为HTTP请求传递?

Jquery 如何在Python中接收对象数组作为参数,并使用AJAX作为HTTP请求传递?,jquery,python,arrays,ajax,flask,Jquery,Python,Arrays,Ajax,Flask,我的ajax调用如下所示: $.ajax({ url: "/doSomeCoolThingOnServer", type: "POST", async: false, data: { simple_string: "Variable sent from client side", array_of_strings: ["John", "George"], array_of_objects: [ { city:

我的ajax调用如下所示:

  $.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上以dict数组的形式接收对象的数组,但返回的却是空数组

@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中使用AJAX接收作为HTTP POST请求传递的参数的对象数组?

您可以使用
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))