使用Cherrypy和jQuery / AJAX从Python获取数据

不幸的是,我没有得到ajax与cherrypy正常工作。 这是我的python代码:

from mako.template import Template from mako.lookup import TemplateLookup import cherrypy import os import json CURDIR = os.getcwd() cherrypy.config.update({ "tools.staticdir.root" : CURDIR, "tools.staticdir.dir" : "static", "tools.staticdir.on" : True }) # Loopuoobjekt für die Templates tmplLookup = TemplateLookup(directories=['templates']) # Liefert das Gerenderte Template zurück def serve_template(templatename, **tmpl_vars): template = tmplLookup.get_template(templatename) return template.render(**tmpl_vars) class Root(object): @cherrypy.expose def index(self): return serve_template("index.html") @cherrypy.expose def switch(self, id): print("Licht nr {} wurde geschaltet".format(id)) cherrypy.response.headers["Content-Type"] = "application/json" return json.dumps({"text" : "schalter {} ".format(id)}) cherrypy.quickstart(Root()) 

这是我的html模板:

     $(document).ready(function() { $("button").click(function() { $.ajax({ url: "switch", type: "POST", data: {id: $(this).attr('id')}, succes: function(response) { $("#test").html(response); } }); }); });    

Hallo Haus!




如果我按下这4个按钮中的一个,我会在控制台中打印出正确的ID。 上面的例子

 return json.dumps({"text" : "schalter {} ".format(id)}) 

写在我发现的最多的东西上,但遗憾的是这给了我一个错误:

 [09/Apr/2014:15:36:57] HTTP Traceback (most recent call last): File "C:\Python33\lib\site-packages\cherrypy-3.2.4-py3.3.egg\cherrypy\_cprequ est.py", line 656, in respond response.body = self.handler() File "C:\Python33\lib\site-packages\cherrypy-3.2.4-py3.3.egg\cherrypy\_cprequ est.py", line 814, in __set__ raise ValueError(self.unicode_err) ValueError: Page handlers MUST return bytes. Use tools.encode if you wish to re turn unicode. 

所以数据成功发送到cherrypy,但我没有得到它。 任何帮助如何使这个工作?

尝试将@ cherrypy.tools.json_out()添加到您的交换机处理程序中……

 import cherrypy import os import json CURDIR = os.getcwd() cherrypy.config.update({ "tools.staticdir.dir" : CURDIR, "tools.staticdir.on" : True }) # Loopuoobjekt für die Templates # Liefert das Gerenderte Template zurück class Root(object): @cherrypy.expose def index(self): return """      

Hallo Haus!

""" @cherrypy.expose @cherrypy.tools.json_out() def switch(self, id): print("Licht nr {} wurde geschaltet".format(id)) return json.dumps({"text" : "schalter {} ".format(id)}) cherrypy.quickstart(Root())

希望这可以帮助!