B

JavaScript Application Storage and Retrieval with jQuery.getJSON

I’ve had occasion to do some JavaScript development for Adobe AIR and PhoneGap lately. JavaScript always requires the use of HTTP requests for storage and retrieval and I found $.getJSON to be a very attractive option. Unfortunately, there seemed to be a dearth of detailed documentation for it.

Basically, you can retrieve a JSON string from a web service with this method and parse it into a JSON object. However, it’s not quite that simple. You have to configure your web service to provide a very specific response. Take a look at this URL. What I’m doing here is sending my name and email, along with a “jsoncallback,” variable. I’m literally printing that callback to the screen along with the parentheses and a semicolon. This is necessary for jQuery to parse the response. The “jsoncallback” is simply a number generated by jQuery to identify the object.

You can use the code below to get an idea of how to use this in JavaScript, but your most important work will be done on the server side:

$(document).ready(function(){
	var post = 'name=John+Fairfull&email=jfairfull@kmdg.com';
	var url  = 'http://scentyourlife.us/mobile/api/?'+post+'&jsoncallback=?';

	$.getJSON(url, function(json) {
		console.log(json);
	});
});

Tags: ,

Leave a Reply