开发者

How to receive AJAX data in CherryPy

Beginning to climb the ajax learning curve, I'm trying to make a simple ajax call back to my CherryPy application and echo the data sent back to the browser.

My ajax call is working and I can return, for instance, the request method back to the browser.

I cannot, however, find the data sent by browser in the request object inside my CherryPy handler. Here is my CherryPy handler, cribbed from 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

and here's my 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>    

Using this code my browser receives back a response of "POST (no body found)".

What I want to do is learn, in my CherryP开发者_运维知识库y handler, that I was sent a word value of "HELLO".

If I uncomment the line body = simplejson.loads(rawbody) I receive an HTML Status of 500 back from CherryPy. The same happens if I try to decorate my index() function with @cherrypy.tools.json_in().


Since you have set processData to false and you are passing over an object you are sending over a stringified version of your data object - and there is nothing to see.

Either:

  1. Call JSON.stringify on your data object before sending it over (which should make your simplejson.loads call work).
  2. Remove your processData attribute and let jQuery send the request over as a normal URL-encoded request (and you can access your variables through request.params["word"]).


word may be in cherrypy.request.params already. Check in there?

http://www.cherrypy.org/wiki/RequestObject#params

I don't think jQuery converts the stuff you put into data as a JSON object. http://api.jquery.com/jQuery.ajax/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜