Javascript 如何使用jquery ajax将json对象正确地传递给flask服务器
我想将包含嵌套对象的json对象从客户端传递到服务器 在客户端,我的数据结构如下所示:Javascript 如何使用jquery ajax将json对象正确地传递给flask服务器,javascript,python,ajax,json,flask,Javascript,Python,Ajax,Json,Flask,我想将包含嵌套对象的json对象从客户端传递到服务器 在客户端,我的数据结构如下所示: var response = {}; response['screening'] = '1'; response['assistance'] = 'wheelchair access'; response['guests'] = {}; response['guests']['1'] = {} response['guests']['1']['first'] = 'John' response['guests
var response = {};
response['screening'] = '1';
response['assistance'] = 'wheelchair access';
response['guests'] = {};
response['guests']['1'] = {}
response['guests']['1']['first'] = 'John'
response['guests']['1']['last'] = 'Smith'
response['guests']['2'] = {}
response['guests']['2']['first'] = 'Dave'
response['guests']['2']['last'] = 'Smith'
$.ajax({
type: "POST",
url: window.location.pathname,
data: response
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
我的ajax调用如下所示:
var response = {};
response['screening'] = '1';
response['assistance'] = 'wheelchair access';
response['guests'] = {};
response['guests']['1'] = {}
response['guests']['1']['first'] = 'John'
response['guests']['1']['last'] = 'Smith'
response['guests']['2'] = {}
response['guests']['2']['first'] = 'Dave'
response['guests']['2']['last'] = 'Smith'
$.ajax({
type: "POST",
url: window.location.pathname,
data: response
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
将此数据发布到使用python flask运行的服务器后,我使用request.form对象检查从客户端发布的内容。我希望数据的结构与此相同,但这是服务器上的输出:
ImmutableMultiDict([('guests[1][first]', u'John'), ('screening', u'2'), ('guests[2][last]', u'Smith'), ('guests[2][first]', u'Dave'), ('assistance', u'wheelchair access'), ('guests[1][last]', u'Smith')])
如您所见,response['guests']对象被展平,其所有子对象都被展平,例如:
“客人[2][第一位]”
。。。只是一个字符串,而不是它们的父响应['guests']的元素
是否有更好的方法将此数据块从客户端发送到服务器,并正确维护其结构
谢谢 您可以将对象作为JSON字符串发送:
var data = {
screening: '1',
assistance: 'wheelchair access',
guests: [
{
first: 'John',
last: 'Smith'
},
{
first: 'Dave',
last: 'Smith'
}
]
};
$.ajax({
type: 'POST',
url: window.location.href,
data: JSON.stringify(response),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
}).done(function(msg) {
alert("Data Saved: " + msg);
});
然后使用
request.json
访问它。在客户端,需要将该javascript对象转换为json字符串。为此,您可以使用以下方法:
JSON.stringify(my_object) // This will return a string that you can pass in you ajax request
然后在服务器端,需要使用json模块将该对象转换为python词汇表:
import simplejson
my_new_object = simplejson.loads(my_json) // my_json is my_object from the client (previously called my_object)
我的新对象现在是一个python字典,你可以用它做任何你想做的事情完全有效!谢谢有一件事是,.done()方法永远不会执行,即使我可以在我的服务器上看到数据,当我检查chrome dev network选项卡时,这个请求有一个POST 200 OK。不要介意上面的评论。我需要jsonify我的服务器响应。再次感谢你在这方面的帮助。