passing Python data to a javascript function

Benjamin Kaplan benjamin.kaplan at case.edu
Wed Oct 26 18:58:07 EDT 2011


On Wed, Oct 26, 2011 at 6:18 PM, Bill Allen <wallenpb at gmail.com> wrote:
>
> I am writing a Python CGI and am needing to pass a data value from Python to a javascript function.   My understanding is that I should use JSON as the middleman.  However, I have not found a good example of doing this.   The piece of data is a simple integer, but I could easily covert that to a string first if necessary.   Here is what I am trying, but unsuccessfully.  I am sure that I have more than one issue in this code.
>
>
>
> #!/usr/bin/python
>
> import json, os, cgi, cgitb
> cgitb.enable()
>
> pid = [{'p':str(os.getpid())}]
> pid_data = json.dumps(pid)
>
> print "Content-type: text/html"
> print
>
> print """
> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
> <html xmlns="http://www.w3.org/1999/xhtml">
> <head><title>Test Page</title>
> <script type="text/javascript">
> function showPId(pid_data)
> {
> var a_pid=eval("(" + pid_data + ")");
> document.getElementById('txt').innerHTML=a_pid;
> }
> </script>
> </head>
> <body onload="startTime({0})">
>
> <center><div id="txt"></div></center><br>
>
> </body>
> </html>""".format(pid_data)
>

You're making this much more difficult than it needs to be. JSON is
used for sending data to JavaScript, meaning the JavaScript asks the
server for a bunch of data, the server sends the client JSON, and
everyone is happy. In your case, the information is available when the
javascript is being generated so you can just pass in the number, no
JSON needed.



More information about the Python-list mailing list