问题
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. Then I am doing a few operations with json and finally I want to send it back to client side. So the question is how to return modified json to the client side (browser).
Server side:
@cherrypy.expose
def drawChart(self):
__test = cherrypy.request.body.read().strip()
logging.debug(__test)
#...some operations with data
Client side:
function send(JsonArray){
$.ajax({
url: '/drawChart',
type: 'post',
contentType: 'application/json',
dataType: 'json',
success: console.log("Success!"),
data: JsonArray
});
}
回答1:
Just change to this line instead of what you have...
success: drawChart,
EDIT: Oh - and change your handler to this:
def drawChart(self, data):
Hope this helps!
回答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
}
}
class App:
@cherrypy.expose
def index(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()
def someendpoint(self):
yourDict = cherrypy.request.json
yourDict['foo'].append('baz')
return yourDict
if __name__ == '__main__':
cherrypy.quickstart(App(), '/', config)
回答3:
My approach is:
@cherrypy.expose
def drawChart(self, coordinates):
cherrypy.response.headers['Content-Type'] = 'application/json'
listOfCoordiantes = randomData(coordinates)
return json.dumps(dict(Coordinates=listOfCoordiantes))
来源:https://stackoverflow.com/questions/31427742/send-back-json-to-client-side