Quickly Creating Ajax Web Demos

In about 50 lines of Python code, you can create the skeleton for a web demo that uses Ajax. This way you can have an interactive demo with HTML links, access to your executables and scripts, etc.; but you’re now free from the system restrictions of JavaScript (which exist for security reasons).

The reason why the 50 lines is impressive is that in order to free yourself from the system restrictions of JavaScript, your web page needs to communicate data back and forth with a web server, and potentially with a database if you have lots of persistent data. Usually you have to install and configure all sorts of servers and settings to get this working.

Since I want my demo to exist within a self-contained directory, Python’s batteries included philosophy comes to the rescue. With WSGI and SQLite, I can (1) create a minimalistic web server that delivers a JavaScript demo and can (2) select what to display from potentially massive amounts of data.

It’s just one file that runs the server. I can then open my browser to “localhost:8000” and the demo can proceed. Of course, I just placed a skeleton below. You can make things more fancy regarding Ajax and JSON as well as by using more heavy-weight WSGI implementations than wsgiref.

Update: a Vim ‘:TOhtml’ issue was fixed in the code below

from wsgiref.simple_server import make_server

ajax_html = """

<title>AJAX + wsgiref Demo</title>
<script language="Javascript">
function ajax_send()
    hr = new XMLHttpRequest();

    hr.open("POST", "/", true);

    hr.onreadystatechange = function()
        if (hr.readyState == 4)
            document.getElementById("result").innerHTML =

<form name="f" onsubmit="ajax_send(); return false;">
        <input name="word" type="text">
        <input value="Do It" type="submit">
    <div id="result"></div>

def intact_app(environ, start_response):
    if environ["REQUEST_METHOD"] == "POST":
        start_response("200 OK", [("content-type", "text/html")])
        clen = int(environ["CONTENT_LENGTH"])
        return [environ["wsgi.input"].read(clen)]

        start_response("200 OK", [("content-type", "text/html")])
        return [ajax_html]

httpd = make_server("", 8000, intact_app)