POST data to Python CGI script via jQuery AJAX

梦想的初衷 提交于 2019-12-03 03:47:28

I believe that the "data" inside the $.ajax should be like a hash of a key-value pairs. try:

$.ajax(
....
  data: {
    a: "aa",
    b: "bb"
  }
...

If you see in the div something like:

MiniFieldStorage('a', 'aa')

Then you should access it via:

my_param = cgi.getfirst('a')

print "Content-Type: text/html\n"
print my_param

If it's still not working, can you test it via GET instead of POST ? In addition, what's the structure of the AJAX file(s) that you're accessing ? ( is the file inside a sub-directory ? etc... )

I figured out that the data needs to be formatted as key-value pairs, like so:

$.ajax({
            url: "http://localhost/cgi-bin/variousTests/post.py",
            type: "POST",
            data: {foo: 'bar', bar: 'foo'},
            success: function(response){
                    $("#div").html(response);
                }
       });

In the Python script, I used this code to get the data from the POST request (it works the exact same way if a GET request is used):

#!/usr/bin/python

import cgi, cgitb 
cgitb.enable()  # for troubleshooting

#the cgi library gets vars from html
data = cgi.FieldStorage()
#this is the actual output
print "Content-Type: text/html\n"
print "The foo data is: " + data["foo"].value
print "<br />"
print "The bar data is: " + data["bar"].value
print "<br />"
print data
  1. I think you need to use a newline with the content type printing.

    print "Content-Type: text/html\n"

  2. Also, you need to provide the parameter name with your variable data. Assuming you are posting the value "xyz" with the parameter "param". So it should be: data["param"] at where the xyz resides.

    print data["xyz"]

  3. If the error still persist, then browse the url localhost/cgi-bin/post.py from the browser and check what does it return(with a GET parameter for testing of course).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!