CherryPy How to respond with JSON?

In my controller/request-handler, I have the following code:


def monkey(self, **kwargs):
  cherrypy.response.headers['Content-Type'] = "application/json"
  message = {"message" : "Hello World!" }
  return message
monkey.exposed = True

And, in my view, I've got this javascript:


$(function() {
  var body = document.getElementsByTagName("body")[0];
  $.ajaxSetup({ 
    scriptCharset : "utf-8",
    contentType: "application/json; charset=utf-8"
  });
  $.post("http://localhost/wsgi/raspberry/monkey", "somePostData",
    function(data) {
      try{
        var response = jQuery.parseJSON(data);
        body.innerHTML += "" + response + "";
      }catch(e){ 
        body.innerHTML += "" + e + "";
      }
    }
  );
});

And finally, here's my problem. I get no JSON response and I'm not sure why.

Secondly, would someone be able to explain how to format data in my controller/request-handler response as a JSON response in the simplest way possible, without using tools?

17
задан bitcycle 4 September 2010 в 05:14
поделиться