I'm using cherrypy's standalone server (cherrypy.quickstart()) and sqlite3 for a database.
I was wondering how one would do ajax/jquery asynchronous calls to the database while using cherrypy?
I'm using cherrypy's standalone server (cherrypy.quickstart()) and sqlite3 for a database.
I was wondering how one would do ajax/jquery asynchronous calls to the database while using cherrypy?
The same way you would do them using any other webserver - by getting your javascript to call a URL which is handled by the server-side application.
If you are using CherryPy 3.2.0-rc1 then you can use the decorators @json_in
and @json_out
(see here).
Thus:
@cherrypy.expose
@tools.json_in(on = True)
@tools.json_out(on = True)
def json_test(self):
return { 'message':'Hello, world!' }
will return JSON to the browser, e.g.
$(document).ready(function() {
$.getJSON('/json_test', function(data) {
alert(data.message);
}
}
You need to remember that CherryPy expects JSON posts to have a content type of application/json
, to do that with jQuery, either use $.ajax
and manaully set contentType
or you can use the following convenience function:
$.postJSON = function(url, data, callback) {
$.ajaxSetup({ scriptCharset:"utf-8",
contentType:"application/json; charset=utf-8" });
$.post(url, $.toJSON(data), callback, "json");
}
This function uses the jquery-json plugin, but you could use a different method to convert to JSON.