【问题标题】:Getting Data back from Python with Cherrypy and jQuery/AJAX使用 Cherrypy 和 jQuery/AJAX 从 Python 获取数据
【发布时间】:2014-05-22 18:31:36
【问题描述】:

不幸的是,我没有让 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 模板:

<html>
<head>
    <script src="jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $("button").click(function() {
            $.ajax({
                url: "switch",
                type: "POST",
                data: {id: $(this).attr('id')},
                succes: function(response) {
                    $("#test").html(response);
                } 
            });
        });
    });
    </script>
</head>
<body>
    <h1>Hallo Haus!</h1>
    <button id=1>Licht 1</button> </br>
    <button id=2>Licht 2</button> </br>
    <button id=3>Licht 3</button> </br>
    <button id=4>Licht 4</button>

    <div id=test></div>

</body>
</html>

如果我按下这 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,但我没有取回它。 任何帮助如何让它工作?

【问题讨论】:

  • 我不知道Python 也不知道cherrypy 但我当然希望您使用Network Tab 进行调试

标签: jquery python ajax cherrypy


【解决方案1】:

尝试将@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 """<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("button").click(function() {
        $.ajax({
            url: "switch",
            type: "POST",
            data: {id: $(this).attr('id')},
            success: function(response) {
                alert(response);
                $("#test").html(response);
            } 
        });
    });
});
</script>
</head>
<body>
    <h1>Hallo Haus!</h1>
    <button id=1>Licht 1</button> </br>
    <button id=2>Licht 2</button> </br>
    <button id=3>Licht 3</button> </br>
    <button id=4>Licht 4</button>

    <div id=test></div>

</body>
</html>"""

    @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())

希望这会有所帮助!

【讨论】:

  • 另外,您在 ajax 函数中拼错了成功。
  • 好的,我在我的代码中得到了@cherrypy.tools.json_out() 并直接返回字典,现在我得到另一个错误:TypeError: Chunk '{' is not of type 'bytes'。这就是我返回回复的方式: return {"text" : "schalter {} ".format(id)
  • 好吧,你还是得继续使用 json.dumps... return json.dumps({"text" : "schalter {} ".format(id)})
  • 它现在以 TypeError 结尾:Chunk '"{\\"text\\": \\"schalter 4 \\"}"' is not of type 'bytes'。
  • 嗯。你用的是什么版本的python?我在 3.2 上,它对我来说运行正常。我将使用有效的代码编辑我的答案。
猜你喜欢
  • 2014-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-03
  • 2015-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多