在python中访问Ajax数据

I am newbie in python and am using Python to get the request from AJAX calls but I am getting the code of python as it is inside the AJAX output which I don't want.

AJAX Code :

$.ajax({
        type: "POST",
        url: "hello.py",
        datatype : "json",
        data: { name: "nitin"}
      })
      .done(function(msg) {
           console.log(msg);
           $("div").html("Data : "+msg)
});

Python Code :

import sys
import cgi

sys.stdout.write("Content-Type: application/json")
sys.stdout.write("
") 
sys.stdout.write("
")

form = cgi.FieldStorage()

sys.stdout.write(json.dumps({ 'data': form.getvalue('name')}))

Output : Data : import sys import cgi sys.stdout.write("Content-Type: application/json") sys.stdout.write(" ") sys.stdout.write(" ") form = cgi.FieldStorage() sys.stdout.write(json.dumps({ 'data': form.getvalue('name')}))

Expected Output should be :

Data : Content-Type: application/json

nitin

is your python script marked as executable? see this -

"The Python script is not marked as executable. When CGI scripts are not executable most web servers will let the user download it, instead of running it and sending the output to the user. For CGI scripts to run properly on Unix-like operating systems, the +x bit needs to be set. Using chmod a+x your_script.py may solve this problem."

there is also a sample to test if your server supports CGI -

https://docs.python.org/2/howto/webservers.html#simple-script-for-testing-cgi

Add below 2 lines inside .htaccess file under /home/*/public_html.

Options +ExecCGI 
AddHandler cgi-script .py

Python code should be like that :

import sys
import cgi
sys.stdout.write("Content-Type: application/x-www-form-urlencoded")
sys.stdout.write("
") 
sys.stdout.write("
")
form = cgi.FieldStorage()
name = form.getvalue('name')
print name

Because content-type is of application/x-www-form-urlencoded not application/json. We are getting form values. If want to see the type of content simply print form.headers.