A demo of an Ajax style application

The following code demonstrates how to write a simple Ajax (Asynchronous JavaScript and XML) application. It uses the [http://jsolait.net Jsolait] library to do the hard work of dealing with the XMLHttp object, and Quixote's xmlrpc support to expose methods from the server.

All of the code is in a single module - this isn't an example of good style, although it does demonstrate how a full Quixote application can be built as a single module...

   1 from quixote.directory import Directory
   2 from quixote.util import StaticDirectory, xmlrpc
   3 from quixote import get_request
   4 
   5 import xmlrpclib
   6 
   7 from quixote.publish import Publisher
   8 
   9 def create_publisher():
  10     return Publisher(MyRoot())
  11 
  12 class RPC(object):
  13     def __call__(self, meth, args):
  14         meth = getattr(self, meth, None)
  15         if meth:
  16             return meth(*args)
  17 
  18     def echo(self, *args):
  19         return args
  20 
  21     def get_time(self):
  22         import time
  23         now = time.gmtime(time.time())
  24         return xmlrpclib.DateTime(now)
  25 
  26 RPC = RPC()
  27 
  28 JS = """\
  29 var xmlrpc = importModule("xmlrpc");
  30 var svc = new xmlrpc.ServiceProxy("http://localhost:8080/rpc", ["get_time"]);
  31 
  32 function update() {
  33     var time = svc.get_time();
  34     var txt = document.createTextNode(time);
  35     var sp = document.getElementById("time");
  36     sp.replaceChild(txt, sp.firstChild);
  37 }
  38 """
  39 
  40 TEMPLATE = """\
  41 <html>
  42 <head>
  43 <script type="text/javascript" src="./jsolait/init.js"></script>
  44 <script type="text/javascript" src="./jsolait/lib/xmlrpc.js"></script>
  45 <script type="text/javascript" src="./test.js"></script>
  46 </head>
  47 <body>
  48 Current Time is: <span id="time">0000</span>
  49 <br />
  50 <input type="submit" onclick="return update();">Update</input>
  51 </body>
  52 </html>
  53 """
  54 
  55 class MyRoot(Directory):
  56     _q_exports = ['', 'rpc', 'jsolait', ('test.js', 'test')]
  57 
  58     def _q_index(self):
  59         return TEMPLATE
  60 
  61     def rpc(self):
  62         return xmlrpc(get_request(), RPC)
  63 
  64     def test(self):
  65         return JS
  66 
  67     jsolait = StaticDirectory('/path/to/jsolait')

The code is in sections, as follows:

And that's it! Run the server, point to http://localhost:8080/ and hit the "Update" button. You'll see the time updated each time you press the button, without a reload.

It's not very exciting, but all of the pieces are there...