Reputation: 257
I have a website which contains some JavaScript code. On a different server, I have a python script. I am trying to send data to the python script and then have the python script return some text.
The JavaScript calls the python file with a call like:
//server.example.com/cgi-bin/pythonscript.py?type=ball&color=blue
My first question is how do I read in those parameters (type=ball and color=blue) in the python script? Would using any of these methods work:
parameters=input()
or
parameters=sys.argv[1:]
or
import cgi
parameters=cgi.FieldStorage()
My second question is then how to I send data back to the JavaScript code. Now, I will be sending text back using JSONP (JavaScript uses callback). Will a simple print or return statement work as shown below?
output_text='callback_func('+json.dump(output_info)+');'
print(output_text)
or
return output_text
Thanks for the help!!! It is really appreciated!
Upvotes: 1
Views: 1773
Reputation: 142256
If you're using the cgi
module, then you use FieldStorage
and print
output
Taken from http://docs.python.org/2/library/cgi.html - this can be used as a base that you just tweak slightly...
import cgi
print "Content-Type: text/html" # HTML is following
print # blank line, end of headers
print "<TITLE>CGI script output</TITLE>"
print "<H1>This is my first CGI script</H1>"
form = cgi.FieldStorage()
if "name" not in form or "addr" not in form:
print "<H1>Error</H1>"
print "Please fill in the name and addr fields."
return
print "<p>name:", form["name"].value
print "<p>addr:", form["addr"].value
Upvotes: 1