【发布时间】:2018-06-30 14:07:52
【问题描述】:
我想创建一个遵循 REST 原则的单页应用程序。我已经设法使 GET 和 DELETE 工作,但我还需要 PUT 或 POST 数据。
在失败了一段时间后,我环顾四周,发现了一些示例代码在这里https://gist.github.com/EtienneR/2f3ab345df502bd3d13e 首先,它告诉我设置请求标头可能会有所帮助。但是,完成此操作并遵循确切的示例,对于我希望接收数据的字段,我仍然得到“无”。 我可能遗漏了一些绝对基本的东西,并且环顾四周,我就是找不到它是什么。
在javascript方面我有:
update_px (path_spl, success_ppl, fail_ppl, formdata) {
this.success_p = success_ppl;
this.fail_p = fail_ppl;
var data = {};
data.firstname = "John";
data.lastname = "Snow";
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("POST", path_spl, true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "201") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(json);
}
在 python 方面:
def POST(self, path_spl="NoPathError", id = None, data_opl=None):
print("POST called with path_spl " + path_spl )
if(id != None) :
print(" and id " + id)
print (data_opl)
#process data
return ' '
方法暴露;输出显示我收到了正确的路径和 ID,但即使在我找到的这个示例代码中交换后,数据也只是 None。
我哪里错了?
【问题讨论】:
-
我会首先将 *kwargs 添加到 Python POST 函数中以查看发送了哪些数据。
-
您应该使用
json_in工具装饰处理程序并从cherrypy.request.json以dict 形式检索数据 -
你也可以使用
cherrypy.tools.json_out,你从handler返回的dict会自动变成json。 -
哦,顺便说一句,如果你使用 Fetch API,你的 js 会更好看
标签: javascript python json xmlhttprequest cherrypy