Saturday, December 17, 2005

Fun with Python, JavaScript, and AJAX

As I get further and further away from my work on the VSC, I've found that I better keep up with web development technology or I'll fall quickly behind. To this end, I've started building an JSON enabled contact's database for work. I've found that I've been able to learn very quickly using MochiKit, json-py, and CherryPy. MochiKit is great because it allows you to abstract a lot of the garbage you have to worry about using plain JavaScript.

For example, want to grab some data from your backend using JSON?

<!--assume MochiKit is loaded-->
<script type='text/javascript'>
function showData(data) {
replaceChildNodes("userInput", H3(null, data["userFullName"]), "E-Mail: "+data["email"]);
}
function getData() {
d = doSimpleXMLHttpRequest("http://my.backend/user", {userName:getElement("userInput").value});
e = d.addCallback(evalJSONRequest);
e.addCallback(showData);
}
</script>
<input id='userInput' name='userInput' /><input type='button' value='Get User' onClick="getData()" />
<div id="resultBox">
</div>


This horribly rudimentary example would fetch some user data from a backend process and display it inside of the div with id "resultBox". If you've ever manipulated the DOM with JavaScript, or performed XMLHttpRequest operations with JavaScript, you should be able to see the benefits in this code.

No comments: