2012-08-14 77 views
8

我知道JSON来解决这个问题,但是我在实现它时遇到了问题。这里是我的方法的细节:将数据从Python发送到Javascript(JSON)

  1. 数据都是用Python
  2. 由于数据的大小是动态计算的,所以我需要使用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>&nbsp</td>        
          <td>%s</td> 
          </tr> 
          <tr> 
          <td>parameter 2</td> 
          <td>&nbsp</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>&nbsp</td><td>out_json</td>').appendTo('.app') 

</script>  

感谢您的帮助!

+0

你能解释一下,为什么你要在相同的模板中传递数据,然后生成HTML代码?在你的问题中,我没有看到任何动态加载(如AJAX),只有没有必要的JavaScript代码会生成你无法使用Python生成的模板的一部分。我对么? – Tadeck 2012-08-14 20:12:03

+0

@Tadeck,使用JavaScript的原因是因为我需要使用JavaScript来创建html表格。另外,我的数据的大小是动态的。所以我认为最好使用JSON将数据传递给JavaScript并让它处理它。另外,我还需要使用Jqplot来生成数字。目前,我在隐藏的html表中生成所有值,并让JavaScript通过选择id名称来获取它们。但我认为应该有更好的方法来做到这一点。 – 2012-08-14 20:29:09

+0

@Tao,数据是动态更新的吗?用户的意思是看不到页面刷新时动态更改数据?如果它是动态的,那么您需要AJAX代码才能从仅返回JSON(不含HTML)的URL请求JSON数据。如果数据在页面加载时已知,那么您只需将JavaScript数据结构添加到页面模板即可。不需要JSON或AJAX。 – jiggy 2012-08-14 20:36:03

回答

11

你不必为 “落实” JSON,Python带有一个内置的lib中,被称为simplejson,您可以用正常的饲料类型的字典:

try: 
    import simplejson as json 
except: 
    import json 
out = {'key': 'value', 'key2': 4} 
print json.dumps(out) 

编辑: 为tadeck指出:,simplejson 应该更先进的日期和不等于JSON,但是有机会的话,由于它是externaly保持

EDIT 2 simplejson不可用基于这个答案的讨论,并在页面上的讨论,我认为,最好的办法是这样的事情:

蟒蛇

# [...] generate dynamic data [...] 
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" data-dynamic="%s">""" % json.dumps(your_generated_data_dict) 
#tr/td elements and templating as needet 
self.response.out.write(html) 

的JavaScript

$(function(){ 
    var your_generated_table = $('table'), 
     dynamic_data = JSON.parse(your_generated_table.attr('data-dynamic')); 
}); 

然后你就可以得到与python字典作为javascript对象完全相同的结构。

+2

这个库在python2.6及更高版本中只是'json'。 – stderr 2012-08-14 20:10:59

+0

感谢您更新我,它已经有一段时间了... – DesertEagle 2012-08-14 20:15:19

+0

感谢您的建议。你能否给我一个关于如何将json.dumps结合到我的案例中的提示(我需要渲染它吗?因为我需要让JavaScript来查看它)? – 2012-08-14 20:30:32