Je connais JSON pour résoudre ce problème, mais j'ai des problèmes dans sa mise en œuvre. Voici le détail de mon approche:
Code HTML (ci-dessous est une section de mon code HTML pour créer la page de sortie):
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> </td> <td>%s</td> </tr> <tr> <td>parameter 2</td> <td> </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)
Code JavaScript (J'utilise JavaScript pour créer des tableaux d'entrées supplémentaires sur le nom de fichier fly: '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> </td><td>out_json</td>').appendTo('.app') </script>
Merci pour l'aide!
Vous ne devez pas "implémenter" JSON, python est livré avec une lib simplejson
, appelée simplejson
, que vous pouvez alimenter avec des dicts normaux:
try: import simplejson as json except: import json out = {'key': 'value', 'key2': 4} print json.dumps(out)
EDIT: comme l'a souligné Tadeck, simplejson devrait être plus à jour et n'est pas égal à json, mais il y a une chance, simplejson n'est pas disponible car il est maintenu externally
EDIT 2: en fonction de la discussion dans cette réponse et de la discussion sur la page, je pense, la meilleure approche serait quelque chose comme ça:
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')); });
Vous avez alors exactement la même structure que votre python dict en tant qu'objet javascript.