Eric Dauenhauer
Eric Dauenhauer

Reputation: 759

How to use AJAX to receive content from Python

I am trying to use AJAX to update a table with data returned from a Python script. When I request the Python script using AJAX, the returned text is the entire python script file, not just the content in the print commands.

My AJAX file:

...standard loadXMLDoc function with callback from W3C AJAX tutorial...


function doNow()
{

loadXMLDoc("cgi-bin/get.py",function()
  {
  if (request.readyState==4 && request.status==200)
    {
    document.getElementById("active_items").innerHTML=request.responseText;
    }
  });
}

window.onload=doNow();

For simplicity, I've used python files as simple as:

print("<div>something</div>")

or

import cgi
import cgitb
cgitb.enable(display=0, logdir="/path/to/logdir")

if __name__ == "__main__":
    print("Content-type:text/html\n\n")
    print("<div>something</div>")

When I load the page, the content of <div id="active_items"> is:

print("
something
")

I have already:

I'm sure I'm missing something obvious, but I would love some help!

Upvotes: 0

Views: 127

Answers (1)

mhawke
mhawke

Reputation: 87074

Add to the top of your Python file (assumes *nix environment):

#!/usr/bin/env python

If you haven't already, ensure that your web server treats .py Python scripts as CGI scripts. An example for Apache is this directive:

  <Directory /srv/www/yoursite/public_html>
        Options +ExecCGI
        AddHandler cgi-script .py
    </Directory>

Upvotes: 2

Related Questions