Getting Data back from Python with Cherrypy and jQuery/AJAX

拥有回忆 提交于 2019-12-06 06:14:51

Try adding @cherrypy.tools.json_out() to your switch handler...

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

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!