Since the iBlog example went away, it was too complex to understand easily, there has been a need for an example of how to do use AJAX and JSON together. JSON is a great way to retrieve data from a server since the data is easily converted into one or more JavaScript objects. The QuickConnectiPhone framework makes it very easy to make JSON requests and I have created an example called JSONDataExample that will be included in QC 1.5 Beta 4.
For the JSONDataExample application I found an open server that can serve up JSON strings. It is a Yahoo! image description service. I'll use this service in this example.
To start with, here is the final product running in the emulator and launched from Dashcode.
mapCommandToBCF('pictures', loadPictureDataBCF);
mapCommandToVCF('pictures', displayPictureDataVCF);
Next we map the pictures command to a View Control Function, displayPictureDataVCF, that is responsible for updating the display based on the data retrieved from the service. Having completed our mappings for the pictures command we can now create the two control functions.
The loadPictureDataBCF function is created in the functions.js file and makes use of the QuickConnectiPhone AJAX wrapper ServerAccessObject. This wrapper is designed to make your use of AJAX as simple as possible.
The code below shows a new ServerAccessObject being created. The constructor is passed the URL of the service without any parameters.
function loadPictureDataBCF(parameters){
var pictureService = newServerAccessObject('http://search.yahooapis.com/ImageSearchService/V1/imageSearch');
pictureService.getData(ServerAccessObject.TEXT, true,'appid=YahooDemo&query=england&output=json');
}
Once pictureService has been created it is now ready for use. Since we are retrieving data from the server we use the ServerAccessObject's getData method. The three parameters are:
function displayPictureDataVCF(results, parameters){
var dataObject = JSON.parse(results[0].data);
var resultSet = dataObject.ResultSet;
var overViewDisplay = document.getElementById('overView');
overView.innerHTML = 'Total Results: '+resultSet.totalResultsAvailable;
overView.innerHTML += '<br/>Results Retrieved: '+resultSet.totalResultsReturned+'<hr/>';
var allImageDescriptions = resultSet.Result;
var numImageDescriptions = allImageDescriptions.length;
var body = document.getElementsByTagName('body')[0];
console.log(body);
for(var i = 0; i < numImageDescriptions; i++){
var anImageDescription = allImageDescriptions[i];
var aDisplay = document.createElement('div');
aDisplay.className = 'imgDisplay';
body.appendChild(aDisplay);
var aThumbnail = document.createElement('img');
aThumbnail.src = anImageDescription.Thumbnail.Url;
aDisplay.appendChild(aThumbnail);
}
}
Once we have the JavaScript object we iterate over all of the image descriptions, build elements to display the data and add them to the body of the page being displayed. We are now done.