我正在尝试使用AJAX将对象发布到Flask。当对象很简单时,代码工作正常,但是当对象包含嵌套对象时,Flask会以奇怪的格式接收数据。
这是AJAX POST:
var req = "commit_url";
var data = {"longURL":"www.google.com",
"product":"FIN",
"project":"Zeus",
"platform":"Twitter",
"theme":["Tech"],
"owner":"Tom"};
var submitData = {"req":req, "data":data};
console.log(submitData)
$.ajax({
url: "http://xxx.xxx.xxx.xxx:5000/",
data: submitData,
type: 'POST',
success: function(response) {
var result = JSON.parse(response);
printShortURL(result.shortURL);
},
error: function(error) {
alert("Error contacting the server. See console for details.")
console.log(error);
}
});
当我提交数据时,控制台会显示:
{"req":"commit_url","data":{"longURL":"www.google.com","product":"FIN","project":"Zeus","platform":"Twitter","theme":"["#Tech"]","owner":"Tom"}}
这是Flask中的python:
@app.route("/", methods=['POST'])
def getData():
f = request.form;
print f
req = f['req'];
print req
longURL = request.form['data[longURL]'];
print longURL
product = request.form['data']['product'];
print product
shortURL = '4Fi92v';
return json.dumps({'status':'OK','shortURL':shortURL});
以下是我在Flask中获得的结果:
ImmutableMultiDict([('data[longURL]', u'www.google.com'), ('data[project]', u'Zeus'), ('data[theme][]', u'#Tech'), ('data[owner]', u'Tom'), ('data[product]', u'FIN'), ('req', u'commit_url'), ('data[platform]', u'Twitter')])
commit_url
www.google.com
xxx.xxx.xxx.xxx - - [06/Feb/2018 12:21:08] "POST / HTTP/1.1" 400 -
正如您所看到的那样,将关键字改为“数据[项目]”而不是将“数据”保留为对象。我可以访问数据,但我希望能够将整个'data'对象传递给另一个函数,而不必遍历所有变量。
我很确定问题出在javascript上,但我尝试使用JSON.parse和JSON.stringify,但我没有成功。
答案 0 :(得分:0)
以grpc
字符串形式发送数据json
。在后端,您将获得JSON.stringify
对象以将其转换为dict.user ImmutableMultiDict
方法。
to_dict()
然后在你的后端做
var req = "commit_url";
var data = {"longURL":"www.google.com",
"product":"FIN",
"project":"Zeus",
"platform":"Twitter",
"theme":["Tech"],
"owner":"Tom"};
var submitData = {"req":req, "data":data};
console.log(submitData)
$.ajax({
url: "http://xxx.xxx.xxx.xxx:5000/",
data: JSON.stringify(submitData),
type: 'POST',
success: function(response) {
var result = JSON.parse(response);
printShortURL(result.shortURL);
},
error: function(error) {
alert("Error contacting the server. See console for details.")
console.log(error);
}
});