【发布时间】:2011-11-26 12:42:26
【问题描述】:
开始爬上 ajax 学习曲线,我正尝试对我的 CherryPy 应用程序进行简单的 ajax 回调,并将发送回浏览器的数据回显。
我的 ajax 调用正在工作,例如,我可以将请求方法返回给浏览器。
但是,我无法在 CherryPy 处理程序内的请求对象中找到浏览器发送的数据。这是我的 CherryPy 处理程序,抄自 this question:
class Contact:
def index(self):
cl = cherrypy.request.headers['Content-Length']
rawbody = cherrypy.request.body.read(int(cl))
body = None
#body = simplejson.loads(rawbody)
if body is None:
return cherrypy.request.method + ' (no body found)'
else:
return cherrypy.request.method + ' ' + body
index.exposed = True
这是我的 Javascript:
<script type="text/javascript">
function SendContactEntry() {
$.ajax( {type: "POST",
url: "/contact/",
data: { word: "HELLO" },
processData: false,
cache: false,
contentType: "application/json",
dataType: "text",
success: function (response){
alert(response);
}
}
);
}
</script>
使用此代码,我的浏览器会收到“POST(未找到正文)”的响应。
我想做的是在我的 CherryPy 处理程序中了解我收到了一个 word 值“HELLO”。
如果我取消注释 body = simplejson.loads(rawbody) 行,我会收到来自 CherryPy 的 HTML 状态 500。如果我尝试用@cherrypy.tools.json_in() 装饰我的 index() 函数,也会发生同样的情况。
【问题讨论】: