The “X” in AJAX stands for XML. But XML is redundant for internet transmission. There’s a better replacement called JSON. JSON is easy and lightweight and efficient to use for all browsers. To use JSON for this TurboGears example, we just have to tell TurboGears that we want to use it via a second @expose() decorator.
@expose(template="tutorial.templates.welcome") @expose("json") def index(self): records = ['iterable', 'items'] return dict(records = records)
Now, if point your browser at http://localhost:8080/index?tg_format=json, you’ll see your records in JSON format.
This easy conversion to JSON is the other use for returning a dictionary. In standard CherryPy methods, you can return a string containing the rendered page. You can do that with TurboGears as well, but a free JSON interface is a pretty good reason to to it the TurboGears way. You can return as many formats as you likeby stacking more @expose() decorators. Check out the @expose reference </1.0/ExposeDecorator> article for details.
The first thing we need to do is have MochiKit included in all of our pages. This can be done by editing the master.html file or by having TurboGears add it as a widget.
Open the tutorial/config/app.cfg. This file controls environment-independent settings like identity and output encoding. Search through the file for the tg.include_widgets setting, uncomment it, and modify it like so:
tg.include_widgets = ['turbogears.mochikit']
After making this configuration change, restart the server. The auto-reload functionality only detects changes to Python files.