简体   繁体   English

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

[英]Send data from Python to Javascript (JSON)

I know JSON to solve this problem, but I have problems in implementing it. 我知道JSON可以解决这个问题,但我在实现它时遇到了问题。 Here is the detail of my approach: 这是我的方法的细节:

  1. Data are calculated in Python 数据以Python计算
  2. Since the size of data is dynamic, so I need to use JavaScript to create extra HTML table rows for my outputs. 由于数据大小是动态的,因此我需要使用JavaScript为输出创建额外的HTML表行。 As a result, I need to pass data from Python to JavaScript to let Javascript to 'see' the data. 因此,我需要将数据从Python传递给JavaScript,让Javascript“看到”数据。

HTML Code (below is a section of my HTML code to create the output page): 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 Code (I use JavaScript to create additional inputs tables on the fly filename:'outputpage_js.html'): 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>    

Thanks for the help! 谢谢您的帮助!

you don't have to "implement" JSON, python comes with a built in lib, called simplejson , which you can feed with normal dicts: 你不必“实现”JSON,python附带一个内置的lib,名为simplejson ,你可以用普通的dicts提供:

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

EDIT: as tadeck pointed out, simplejson should be more up-to-date and is not equal to json, but there is a chance, simplejson is not available due to it is maintained externaly 编辑:正如塔德克指出的那样,simplejson 应该是更新的并且不等于json,但是有一个机会,simplejson因为它被保持为外部而不可用

EDIT 2: based on the discussion in this answer and the discussion on the page, i think, the best approach would be something like that: 编辑2:根据本回答中的讨论和页面上的讨论,我认为,最好的方法是这样的:

python 蟒蛇

# [...] 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 JavaScript的

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

you then have the exact same structure your python dict has as a javascript object. 然后你的python dict具有与javascript对象完全相同的结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM