简体   繁体   中英

Error in Executing a python script when a button is clicked (JS, AJAX)

I have this code in which I expect that if I click the connect button, test.py will be executed in the background. I found this solution online but I can't seem to get it working.

My Python script:

#!/usr/bin/python
import os

def main():
    os.startfile("notepad.exe")
    return "okay"

if __name__ == "__main__":
    main() 

My JavaScript code:

function myFunction(){
    $.ajax({
        url: "test.py",
        success: function() { 
            alert("working");
        },
        error: function(){
            alert("not working");
        }
    });
};

Any help would be appreciated.

Assuming you want to call it as an CGI script your Python code should start with outputing the HTTP headers like below:

#!/usr/bin/python
import os

def main():
    try:
        os.startfile("notepad.exe")
    except:
        print "Status: 500 Internal Server Error"
        print "Content-type: text/plain"
        print
        print "error"
    else:
        print "Status: 200 OK"
        print "Content-type: text/plain"
        print
        print "okay"

if __name__ == "__main__":
    main()

Then place it in /cgi-bin/ directory of your webserver root. There comes part I'm not sure about. You has set interpreter of your Python script to "/usr/bin/python" what suggest using Linux. If that is the case you should replace "notepad.exe" with whatever is the valid editor command of your Linux distribution. Also remember to make the CGI script executable:

chmod +x test.py

On the other hand if you are using Windows, you should instead edit the first line of your script to reflect the different Windows paths, eg:

#!c:/Python27/python.exe

You may come into some more problems with your webserver configuration if you want to use CGI on Windows, however.

When you already have CGI script working, alter the URL in your AJAX call to look for it in /cgi-bin/ , ie:

        url: "/cgi-bin/test.py",

If you come to any problems with your CGI script it may be useful to use cgitb to debug it, bu adding following lines in your script, just before import os :

import cgitb
cgitb.enable()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM