开发者

How does one do async ajax calls using cherrypy?

开发者 https://www.devze.com 2022-12-15 11:53 出处:网络
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开发者_JAVA百科 using

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开发者_JAVA百科 using cherrypy?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号