我知道JSON來解決這個問題,但是我在實現它時遇到了問題。這裏是我的方法的細節:將數據從Python發送到Javascript(JSON)
- 數據都是用Python
- 由於數據的大小是動態計算的,所以我需要使用JavaScript來爲我創建輸出HTML額外表行。因此,我需要將數據從Python傳遞到JavaScript,以便讓Javascript「查看」數據。
HTML代碼(下面是我的HTML代碼段創建輸出頁面):
class OutputPage(webapp.RequestHandler):
def func (a,b):
return a+b #just an example
def get(self):
form = cgi.FieldStorage()
chem_name = form.getvalue('chemical_name')
Para1 = form.getvalue('Para1') #get values from input page--user inputs
Para1 = float(Para1)
Para2 = form.getvalue('Para2') #get values from input page--user inputs
Para2 = float(Para2)
out = func (Para1,Para1)
out_json=simplejson.dumps(out) # I need to send out to JavaScript
#writ output page
templatepath = os.path.dirname(__file__) + '/../templates/'
html = html + template.render (templatepath + 'outputpage_start.html', {})
html = html + template.render (templatepath + 'outputpage_js.html', {})
html = html + """<table width="500" class='out', border="1">
<tr>
<td>parameter 1</td>
<td> </td>
<td>%s</td>
</tr>
<tr>
<td>parameter 2</td>
<td> </td>
<td>%s</td>
</tr>
</table><br>"""%(Para1, Para2)
html = html + template.render(templatepath + 'outputpage_end.html', {})
#attempt to 'send' Python data (out_json) to JavaScript, but I failed.
html = html + template.render({"my_data": out_json})
self.response.out.write(html)
app = webapp.WSGIApplication([('/.*', OutputPage)], debug=True)
JavaScript代碼(我用JavaScript來創建動態文件名額外的輸入表:'outputpage_js。 HTML'):
<script>
<script type='text/javascript'>
$(document).ready(function(){
//I assume if my Json statement works, I should be able to use the following argument to create a HTML row
$('<tr><td>Parameter 2</td><td> </td><td>out_json</td>').appendTo('.app')
</script>
感謝您的幫助!
你能解釋一下,爲什麼你要在相同的模板中傳遞數據,然後生成HTML代碼?在你的問題中,我沒有看到任何動態加載(如AJAX),只有沒有必要的JavaScript代碼會生成你無法使用Python生成的模板的一部分。我對麼? – Tadeck 2012-08-14 20:12:03
@Tadeck,使用JavaScript的原因是因爲我需要使用JavaScript來創建html表格。另外,我的數據的大小是動態的。所以我認爲最好使用JSON將數據傳遞給JavaScript並讓它處理它。另外,我還需要使用Jqplot來生成數字。目前,我在隱藏的html表中生成所有值,並讓JavaScript通過選擇id名稱來獲取它們。但我認爲應該有更好的方法來做到這一點。 – 2012-08-14 20:29:09
@Tao,數據是動態更新的嗎?用戶的意思是看不到頁面刷新時動態更改數據?如果它是動態的,那麼您需要AJAX代碼才能從僅返回JSON(不含HTML)的URL請求JSON數據。如果數據在頁面加載時已知,那麼您只需將JavaScript數據結構添加到頁面模板即可。不需要JSON或AJAX。 – jiggy 2012-08-14 20:36:03