Send Back Json To Client Side
I just started developing with cherrypy, so I am struggling a little bit. In client side I am selecting some data, converting it to json and sending to server side via post method.
Solution 1:
Just change to this line instead of what you have...
success: drawChart,
EDIT: Oh - and change your handler to this:
defdrawChart(self, data):
Hope this helps!
Solution 2:
Use CherryPy JSON tools.
#!/usr/bin/env python# -*- coding: utf-8 -*-
import cherrypy
config = {
'global' : {
'server.socket_host' : '127.0.0.1',
'server.socket_port' : 8080,
'server.thread_pool' : 8
}
}
classApp:@cherrypy.expose
defindex(self):
return'''<!DOCTYPE html>
<html>
<head>
<title>CherryPy demo</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript'>
$.ajax({
'type' : 'POST',
'dataType' : 'JSON',
'contentType' : 'application/json',
'url' : '/someendpoint',
'data' : JSON.stringify({'foo': ['bar']}),
'success' : function(response)
{
console.log(response);
}
});
</script>
</head>
</html>
'''@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
defsomeendpoint(self):
yourDict = cherrypy.request.json
yourDict['foo'].append('baz')
return yourDict
if __name__ == '__main__':
cherrypy.quickstart(App(), '/', config)
Solution 3:
My approach is:
@cherrypy.exposedefdrawChart(self, coordinates):
cherrypy.response.headers['Content-Type'] = 'application/json'
listOfCoordiantes = randomData(coordinates)
return json.dumps(dict(Coordinates=listOfCoordiantes))
Post a Comment for "Send Back Json To Client Side"