passing Python data to a javascript function
Bill Allen
wallenpb at gmail.com
Wed Oct 26 23:51:34 EDT 2011
Chris,
Wow, that seems so simple now that I see it. I was dancing around that all
day, but just not landing on it. Thanks so very much for the assist.
--Bill
Final code that works perfectly, passes the value from the Python script to
the javascript correctly:
#!/usr/bin/python
import json, os, cgi, cgitb
cgitb.enable()
pid_data = str(os.getpid())
print "Content-type: text/html"
print
print """
<html>
<head><title>Test Page</title>
<script type="text/javascript">
function showPID(pid){
document.getElementById('txt').innerHTML="js: "+pid;
}
</script>
</head>
<body onload="showPID("""+pid_data+""")">
Hello World!<br><br>
<div id="txt"></div><br>
"""
print "html: "+pid_data+"<br>"
print """
</body>
</html>"""
Output of above code is the following, which is just the PID of the Python
CGI itself at runtime, displayed via javascript and via HTML.
Hello World!
js: 1308
html: 1308
On Wed, Oct 26, 2011 at 21:42, Chris Rebert <clp2 at rebertia.com> wrote:
> On Wed, Oct 26, 2011 at 7:25 PM, Bill Allen <wallenpb at gmail.com> wrote:
>
> The problem is that you're not passing the data at all. You never
> interpolate the pid_data value into the string(s) constituting your
> embedded JavaScript (though you did do it just fine in the pure HTML).
> The Python variable `pid_data` is not somehow magically accessible to
> JavaScript; you must explicitly insert its value somewhere.
>
> <snip>
> > pid_data = str(os.getpid())
> <snip>
> > print """
> <snip>
> > <body onload="showPID(pid_data)">
>
> Change that line to:
> <body onload="showPID("""+pid_data+""")">
>
> As an example, if the PID happens to be 42, then the outputted
> fragment will end up being:
> <body onload="showPID(42)">
>
> As a sidenote, I would recommend using something higher-level than the
> `cgi` module. Python has an abundance of web frameworks and templating
> languages; take your pick.
>
> Cheers,
> Chris
> --
> http://rebertia.com
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20111026/1247443f/attachment-0001.html>
More information about the Python-list
mailing list