Send data from Python to Javascript (JSON)

前端 未结 1 1337
清酒与你
清酒与你 2021-01-05 05:39

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
相关标签:
1条回答
  • 2021-01-05 06:01

    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 讨论(0)
提交回复
热议问题