如何使用cherrypy进行async ajax调用?

1 python ajax jquery asynchronous cherrypy

我正在使用cherrypy的独立服务器(cherrypy.quickstart())和sqlite3作为数据库.

我想知道如何在使用cherrypy时对数据库执行ajax/jquery异步调用?

Sam*_*shi 9

如果你使用的是CherryPy 3.2.0-rc1,那么你可以使用装饰器@json_in@json_out(见这里).

从而:

@cherrypy.expose
@tools.json_in(on = True)
@tools.json_out(on = True)
def json_test(self):
    return { 'message':'Hello, world!' }
Run Code Online (Sandbox Code Playgroud)

将JSON返回给浏览器,例如

$(document).ready(function() {
    $.getJSON('/json_test', function(data) {
        alert(data.message);
    }
}
Run Code Online (Sandbox Code Playgroud)

你需要记住,CherryPy希望JSON帖子的内容类型为application/jsonjQuery,使用$.ajax和manaully设置,contentType或者你可以使用以下便利功能:

$.postJSON = function(url, data, callback) {
    $.ajaxSetup({ scriptCharset:"utf-8", 
                    contentType:"application/json; charset=utf-8" });
    $.post(url, $.toJSON(data), callback, "json");
}
Run Code Online (Sandbox Code Playgroud)

此函数使用jquery-json插件,但您可以使用其他方法转换为JSON.