== 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... {{{#!python from quixote.directory import Directory from quixote.util import StaticDirectory, xmlrpc from quixote import get_request import xmlrpclib from quixote.publish import Publisher def create_publisher(): return Publisher(MyRoot()) class RPC(object): def __call__(self, meth, args): meth = getattr(self, meth, None) if meth: return meth(*args) def echo(self, *args): return args def get_time(self): import time now = time.gmtime(time.time()) return xmlrpclib.DateTime(now) RPC = RPC() JS = """\ var xmlrpc = importModule("xmlrpc"); var svc = new xmlrpc.ServiceProxy("http://localhost:8080/rpc", ["get_time"]); function update() { var time = svc.get_time(); var txt = document.createTextNode(time); var sp = document.getElementById("time"); sp.replaceChild(txt, sp.firstChild); } """ TEMPLATE = """\ <html> <head> <script type="text/javascript" src="./jsolait/init.js"></script> <script type="text/javascript" src="./jsolait/lib/xmlrpc.js"></script> <script type="text/javascript" src="./test.js"></script> </head> <body> Current Time is: <span id="time">0000</span> <br /> <input type="submit" onclick="return update();">Update</input> </body> </html> """ class MyRoot(Directory): _q_exports = ['', 'rpc', 'jsolait', ('test.js', 'test')] def _q_index(self): return TEMPLATE def rpc(self): return xmlrpc(get_request(), RPC) def test(self): return JS jsolait = StaticDirectory('/path/to/jsolait') }}} The code is in sections, as follows: * Lines 7-10 - expose a publisher creation factory, for the server script * Lines 12-26 - a class which handles the available XML-RPC methods * Lines 28-53 - some inline chunks of HTML and Javascript (yes, I know this is a hack, but I wanted to keep the demo simple and self-contained) * Lines 55-67 - the meat of the site. The jsolait code is exposed as a static directory, and the RPC service at the URL /rpc. Finally, the HTML and some supporting JavaScript is exposed. 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...