[英]How can I pass an object with an embedded object from JavaScript (jQuery/ajax) to Python (Flask)?
I am attempting to pass structured data from a web page to a flask handler, but I am getting key errors. 我试图将结构化数据从网页传递到烧瓶处理程序,但出现关键错误。
In the web page's JavaScript, I have an object that has two elements, one a value, the other an object. 在网页的JavaScript中,我有一个包含两个元素的对象,一个是值,另一个是对象。
The problem is on the Flask/Python side. 问题出在Flask / Python方面。 I can get the first element (
"cid"
) with this: 我可以这样获得第一个元素(
"cid"
):
print request.form ["cid"]
That works. 这样可行。 But, I can't access or get to any of the att(ribute) values (
"att"
). 但是,我无法访问或获取任何att(ribute)值(
"att"
)。
So, this, request.form ["att"]
returns KeyError: 'att'
因此,
request.form ["att"]
返回KeyError: 'att'
I am able to access request.form["att[sw1]"]
but this is flattening my data type. 我可以访问
request.form["att[sw1]"]
但是这使我的数据类型扁平化。
I'd like to get the att elements as a list or dictionary so that I can loop through them in my application. 我想以列表或字典的形式获取att元素,以便可以在应用程序中遍历它们。 I essentially want
request.form["att"]["sw1"]
or request.form.att["sw1"]
. 我本质上想要
request.form["att"]["sw1"]
或request.form.att["sw1"]
。
var controllerData = {
sw1 : $('#sw1').val(),
sw2 : $('#sw2').val(),
sw3 : $('#sw3').val(),
sw4 : $('#sw4').val()}
var updateData = {cid : 1, att: controllerData };
$.ajax({
type: "POST",
url: "/SetSettings",
data: updateData,
success: function(d) { },
error: function(d) {alert('Error saving settings!');},
dataType: "json"
});
You must serialize your data object to string with JSON.stringify() . 您必须使用JSON.stringify()将数据对象序列化为字符串。
$.ajax({
type: "POST",
url: "/SetSettings",
data: JSON.stringify(updateData),
success: function(d) { },
error: function(d) {alert('Error saving settings!');},
dataType: "json"
});
PS: Some object, eg window
or object containing cyclic dependencies cannot be serialized this way PS:某些对象,例如
window
或包含循环依赖关系的对象,无法以这种方式序列化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.