Python 在包含 JQuery 时抛出 KeyError

Python throwing KeyError when JQuery included

本文关键字:KeyError JQuery 包含 Python      更新时间:2023-09-26

我有下面的代码,我想在html中设置一个变量。出于某种原因,当我删除 JQuery 时,它可以工作,但是当我放入 JQuery 脚本时,它不起作用。我认为这可能是因为在加载页面时调用了 JQuery,因为如果从按钮调用 JQuery,我可以让它工作。我已经尝试了 %s、%(当前日期)s、{0} 然后是它们的相关输出,但它们似乎都没有奏效。前两个抛出ValueError: unsupported format character ''' (0x27) at index 952,然后{0}导致KeyError: "'n $('"

class Fitbit(object):
@cherrypy.expose
def index(self):
currentDate = (time.strftime("%d/%m/%Y"))
return """<html>
<head>
    <title>Fitbit</title>
    <link href="/static/css/fitbit.css" rel="stylesheet">
    <script>
            $('document').ready(init);
                function init(){
                $('.bar-percentage[data-percentage]').each(function () {
                    var progress = $(this);
                    var percentage = Math.ceil($(this).attr('data-percentage'));
                    $({countNum: 0}).animate({countNum: percentage}, {
                        duration: 2000,
                        easing:'linear',
                        step: function() {
                        // What todo on every count
                            var pct = '';
                            if(percentage == 0){
                                pct = Math.floor(this.countNum) + '%';
                            }else{
                                pct = Math.floor(this.countNum+1) + '%';
                            }
                        progress.text(pct) && progress.siblings().children().css('width',pct);
                        }
                    });
                });
            };
        </script>
</head>
<body>
<h4>{0}</h4>
</body>
</html>""" .format(currentDate)
#return html
index.exposed = True

如果我删除 JQuery,它肯定工作正常并显示日期。任何其他尝试的想法将不胜感激。

由于JavaScript中的所有大括号,您遇到了问题。这会混淆format函数。最好使用模板引擎来渲染 HTML。

但是,如果您想继续使用当前代码,请尝试将 JavaScript/jQuery 代码放入其自己的变量中,然后通过format调用将其插入到 HTML 中。

currentDate = (time.strftime("%d/%m/%Y"))
javascript = """
$('document').ready(init);
function init(){
    $('.bar-percentage[data-percentage]').each(function () {
        var progress = $(this);
        var percentage = Math.ceil($(this).attr('data-percentage'));
        $({countNum: 0}).animate({countNum: percentage}, {
            duration: 2000,
            easing:'linear',
            step: function() {
            // What todo on every count
                var pct = '';
                if(percentage == 0){
                    pct = Math.floor(this.countNum) + '%';
                }else{
                    pct = Math.floor(this.countNum+1) + '%';
                }
            progress.text(pct) && progress.siblings().children().css('width',pct);
            }
        });
    });
};
"""
return """<html>
<head>
    <title>Fitbit</title>
    <link href="/static/css/fitbit.css" rel="stylesheet">
    <script>{0}</script>
</head>
<body>
<h4>{1}</h4>
</body>
</html>""".format(javascript, currentDate)