Friday, 27 May 2011

AJAX and JSON

I recently had to develop a kind of "widget" that interrogates a remote server by means of an asynchronous javascript call. The response was a javascript object defined with JSON syntax. Question was: how do I process it? I found many tutorials that use JSONP techniques (weird yet powerful for cross-site execution) but I don't have control on the remote service. Others suggest an external framework (like jQuery) but I don't like it, I want my own wheel.

So, here come my snippets. First, you make your async call:


xmlhttp = window.XMLHttpRequest?
   new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = parse_function;
xmlhttp.open("GET", service_url );
xmlhttp.send(null);


Then, you handle the response (inside parse_function):


if ( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
   json_data = eval( "(" + xmlhttp.responseText + ")" );
}


This way you get an object filled with usable stuff (json_data). Notice js' eval function and the brackets - those do the trick.

3 comments:

Dave said...

You should really use jQuery :P

Marco S. Nobile said...

I (we) do, adopted for more complex stuff like photo galleries, visual fx and such. This being a widget for federate websites I prefer to keep it clean and light.

Anonymous said...

Your site is just tremendous! Please write more as soon as possible.