views:

532

answers:

2

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?

+1  A: 

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.

Daniel Roseman
Yup. CherryPy doesn't care how you call it as long as it's HTTP. From the server side, AJAX looks just like any other request. You might have to set cherrypy.response.headers['Content-Type'] to 'application/json' or whatever you are returning...
fumanchu
+2  A: 

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.

Sam Doshi