最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Send data from Python to Javascript (JSON) - Stack Overflow

programmeradmin0浏览0评论

I know JSON to solve this problem, but I have problems in implementing it. Here is the detail of my approach:

  1. Data are calculated in Python
  2. Since the size of data is dynamic, so I need to use JavaScript to create extra HTML table rows for my outputs. As a result, I need to pass data from Python to JavaScript to let Javascript to 'see' the data.

HTML Code (below is a section of my HTML code to create the output page):

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'):

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

I know JSON to solve this problem, but I have problems in implementing it. Here is the detail of my approach:

  1. Data are calculated in Python
  2. Since the size of data is dynamic, so I need to use JavaScript to create extra HTML table rows for my outputs. As a result, I need to pass data from Python to JavaScript to let Javascript to 'see' the data.

HTML Code (below is a section of my HTML code to create the output page):

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'):

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

Share Improve this question edited Aug 14, 2012 at 20:24 TTT asked Aug 14, 2012 at 20:03 TTTTTT 4,43413 gold badges76 silver badges129 bronze badges 9
  • Could you explain, why exactly are you trying to pass data in the same template that will then generate HTML code? I do not see any dynamic loading (like AJAX) in your question, only not necessary JavaScript code that will generate part of the template you were not able to generate using Python. Am I correct? – Tadeck Commented Aug 14, 2012 at 20:12
  • @Tadeck, the reason to use JavaScript is because I need to use JavaScript to create html tables. Plus, the size of my data is dynamic. So I think it is better to use JSON to pass data to JavaScript and let it to handle it. In addition, I also need to use Jqplot to generate figures. Currently, I generate all the values in a hidden html table and let JavaScript to get them by selecting id names. But I think there should be a better way to do this. – TTT Commented Aug 14, 2012 at 20:29
  • @Tao, is the data dynamicly updating? Meaning will the user see data change on the fly without a page refresh? If it's dynamic, you would need AJAX code to request the JSON data from a URL that only returns JSON (no HTML). If the data is known when the page is loaded, then you just need to add the JavaScript data structure to your page template. No JSON or AJAX required. – jiggy Commented Aug 14, 2012 at 20:36
  • @jiggy, I guess my case belongs to the second category. I need to use JavaScript to create some html rows and use Jqplot to create plots. But my question is, how could I 'tell' JavaScript parameters created in Python? – TTT Commented Aug 14, 2012 at 20:40
  • 1 @tao.hong: You do not need JavaScript, nor AJAX, if the data you want to display is dynamic. This is because you are already dynamically generating the HTML (see your code). So just generate your HTML from the beginning, fully in Python. The things begin to change when you need the data in the JavaScript for the purposes you mentioned (using in the script, eg. for diagramming). This is the reason for passing JSON. To do that, you can simply generate JSON in Python (simplejson.dumps(some_data)), and place it within HTML's data- attributes (eg. in data-parameters) properly escaped. – Tadeck Commented Aug 14, 2012 at 20:42
 |  Show 4 more comments

1 Answer 1

Reset to default 11

you don't have to "implement" JSON, python comes with a built in lib, called simplejson, which you can feed with normal 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

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:

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

$(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.

发布评论

评论列表(0)

  1. 暂无评论