AJAX - The Complete Reference

(avery) #1

PART III


Chapter 10: Web Services and Beyond 493


Chapter 2 is our best candidate. Response-wise we will of course expect JavaScript—usually
a wrapped JSON packet or some raw JavaScript—to execute. We continue with Flickr as it
provides a remote <script> call interface as well.
In the case of Flickr, we saw that their JSON packet is by default wrapped with a function
call like so:

jsonFlickrApi( {JSON object} )

Here the JSON object is a representation of the <rsp> element found in the typical
RESTful response. Recall that we can change the callback to our own function name by
passing a jsoncallback parameter (jsoncallback=handleResponse). To execute our
<script> tag Web Service approach, we will need to set all the parameters to the service
ourselves, so we make a simple object to hold all of them.

var flickrConfig = {
method : "flickr.photos.search",
api_key : "dc11b-FAKE-KEY-HERE0--a",
safe_search : 1,
per_page : 10,
content_type : 1,
format : "json",
jsoncallback : "handleResponse"
};

Now we set up our payload to contain all the items as well as the search term using our
handy AjaxTCR.data.serializeObject() method:

var payload = "text=" + searchterm;
payload = AjaxTCR.data.serializeObject(payload,flickrConfig,"application/
x-www-form-urlencoded");

Given that since Chapter 9 we’ve supported other transports in our library, we just
indicate we want to use a <script> tag instead of an XHR when making our request:

var url = "http://api.flickr.com/services/rest/";
var options = {method:"GET",
payload:payload,
transport: "script",
statusIndicator : { progress : {type: "text", text:
"Searching...", target: "progress" }}};
AjaxTCR.comm.sendRequest(url, options);

We don’t specify the callback, of course, since the payload will contain it. Now we
should receive a response like so:
Free download pdf