【问题标题】:web.py and JavaScript problemsweb.py 和 JavaScript 问题
【发布时间】:2011-11-23 23:22:28
【问题描述】:

我一直在尝试制作一个结合 web.py 和 JavaScript 的页面,并使用以下代码:

$code: 
     def getContents(fname): 
          a = req.get(fname) 
          return a.content 

<script type="text/javascript"> 
     document.write("$getContents('http://mysite.net')"); 
</script> 

这里,req 传递给我的模板的$def with() 函数,它是Python Requests module 的一个模块对象,我从中执行方法。)

问题是,文档是空白的,这意味着document.write 函数没有输入。有没有解决的办法?我这样做有错吗?

EDIT:函数输出不为空;如果你使用纯 HTML 来打印它,它就可以工作。

提前致谢。

(我也在web.py Google group上发布了这个问题,还没有得到答案。)

【问题讨论】:

  • 可以显示渲染页面的“查看源代码”内容吗?

标签: javascript web.py


【解决方案1】:

您可以在模板全局变量中启用 json 编码器,并在您的 javascript 代码中使用它。

import json
template_globals = {"json_encode": json.dumps}
render = web.template.render(config.template_dir, globals=template_globals, base="layout")

然后在你的模板中

<script>
var obj = $:json_encode({"html": getContents('http://mysite.net')});
document.write(obj.html);
</script>

【讨论】:

    【解决方案2】:

    也许您在呈现的内容中有引号,它会使 javascript 无效。

    【讨论】:

    • 为什么不显示生成页面的来源?很容易看出问题。
    • 来源在pastie.org/2914370;它呈现matoe.co.cc/patcher.txt 进行测试。
    • 问题是你的javascript字符串被换行符打断了。
    • 那么有没有办法逃脱\n 而不是NEWLINE? (你是对的:))
    • 检查我的第二个答案,只需使用 json.dumps 为 javascript 正确编码字符串。这样您就不必担心引号或换行符等。
    猜你喜欢
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2012-11-19
    • 2021-05-02
    • 2018-03-15
    • 1970-01-01
    相关资源
    最近更新 更多