2011-11-23 35 views
0

我一直在試圖使它結合web.py和JavaScript的網頁,並用下面的代碼: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函數沒有輸入。有沒有解決的辦法?我是否以錯誤的方式做這件事?

編輯:函數輸出不爲空;如果您使用純HTML來打印它,它將會正常工作。

在此先感謝。

(我也張貼了這個問題,在web.py谷歌組,沒有得到答案。)

+0

,你能否告訴渲染頁面的「查看源文件」的內容? –

回答

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> 
0

也許你有渲染的內容引號,和它無效的JavaScript。

+0

我試過了,沒有引號;不起作用。 :( – Matoe

+0

爲什麼你不顯示生成頁面的來源?很容易看到問題。 –

+0

來源位於http://pastie.org/2914370;它呈現http://matoe.co.cc /patcher.txt – Matoe