将数据从 Python 发送到 Javascript (JSON)

Send data from Python to Javascript (JSON)

本文关键字:Javascript JSON 数据 Python      更新时间:2023-09-26

我知道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>    

感谢您的帮助!

不必"实现"JSON,python带有一个内置的lib,叫做simplejson,你可以用普通的字典来输入:

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

编辑:正如 Tadeck 指出的那样,SimpleJSON 应该更及时,不等于 JSON,但有可能,SimpleJSON 不可用,因为它是外部维护的。

编辑2:根据本答案中的讨论和页面上的讨论,我认为最好的方法是这样的:

# [...] 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'));
});

然后,您将拥有与 JavaScript 对象完全相同的 Python 字典结构。