passing Python data to a javascript function

Bill Allen wallenpb at gmail.com
Wed Oct 26 18:18:36 EDT 2011


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)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20111026/c5d10da6/attachment-0001.html>


More information about the Python-list mailing list