Skip to main content
 首页 » 编程设计

jquery之如何使用 cherrypy 进行异步 ajax 调用

2025年05月04日28dyllove98

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

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

请您参考如下方法:

如果您使用的是 CherryPy 3.2.0-rc1然后你可以使用装饰器 @json_in 和 @json_out ( see here )。

因此:

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

将JSON返回给浏览器,例如

$(document).ready(function() { 
    $.getJSON('/json_test', function(data) { 
        alert(data.message); 
    } 
} 

您需要记住,CherryPy 期望 JSON 帖子的内容类型为 application/json,要使用 jQuery 做到这一点,请使用 $.ajax 并手动设置contentType 或者您可以使用以下便捷函数:

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

此函数使用 jquery-json插件,但您可以使用不同的方法转换为 JSON。