I have no special talent. I'm only passionately curious - Albert Einstein
Developing jsonp Services for jQuery Comment on Developing jsonp Services for jQuery 0

The documentation for successfully developing jsonp services for use with jQuery is not very straightforward.  The examples consist of a number of ajax calls using jQuery's .ajax and .getJSON functions, but until recently did not contain any examples of performing remote calls to jsonp services.  If you read the documentation for using the jsonp dataType with their ajax function, you will see a link to an article by Bob Ippolito outlining the first proposed jsonp format, and how to use it.  The format documented on Bob's article is not valid when used with jQuery's functions (jQuery doesn't error out, it just doesn't do anything at all).  Their most recent example of using the new Flickr jsonp API sheds light on the format that jQuery really expects for json returned by remote jsonp services.

This article outlines the correct jsonp format that jQuery expects (tested with 1.4.1), and a method for developing jsonp services within Java web applications.  I searched the web for an easy to use JSON tag lib, and found a great project available on Sourceforge.  The taglib APIs are simple to use, and I was up and running in a matter of minutes with my sample web app.  I wanted to test the ability to send not only simple String values in my json object, but I was mostly interested in finding a way to send HTML formatted content through a json object to another server.  This allows me to expose any content managed by a web content management system through a service to external consumers.

jQuery offers two ajax functions which make it easy to retrieve remote content with jsonp as the expected return type.  The getJSON function is the shortcut version of using the ajax function - you don't have to specify the dataType as jsonp every time.  The only trick you need to keep in mind when using the getJSON function is to make sure you add the following query parameter to your remote url:  callback=?.  So, if your url was, for example, http://d.avidmalone.com, you would use the url http://d.avidmalone.com?callback=? in the getJSON function.  jQuery will automatically create a value for the callback parameter.  That parameter will need to be referenced by the server when generating the jsonp response.  Here's my example script:

<script type="text/javascript">

$(document).ready(function(){

    var jsonpUrl = 'http://d.avidmalone.com/SandboxWeb/json.jsp?callback=?

';

    $.getJSON(jsonpUrl, function(data) {
        alert(data);
        $('#tsomeDiv').append(data.content);
    });
});

</script>

As previously mentioned, the callback parameter will automatically be given a value by jQuery, and will need to be integrated into the jsonp service's response.  In my example, I'm using the json-taglib avaliable on Sourceforge to generate my json content.  The jsonp format that jQuery expects is this:

callbackParamValue({jsonpcontent})

The jsonpcontent area is just standard json, nothing new there.  The important thing to note here is that the json content is wrapped in parenthesis, and prefixed with the callback parameter value generated by jQuery - this is always dynamic, which is why the service must be written to accept the parameter and use it to generate the jsonp response.  Without those things, jQuery just won't accept the json content returned from your service.  Here's the example jsonp.jsp I've put together for testing.  To run it, just create a quick web app in Eclipse, add the json-taglib jar file to your WEB-INF/lib, and drop this jsp in your WebContent directory.

<%@ taglib prefix="json" uri="http://www.atg.com/taglibs/json" %>
<%
    response.setContentType("text/javascript");
    System.out.println("Callback param: " + request.getParameter("callback"));
%>
${param.callback}(<json:object prettyPrint="true">
  <json:property name="author" value="Dave Malone"/>
  <json:property name="lastUpdated" value="Feb 1, 2010 02:34:37 PM CST"/>
  <json:property name="title" value="Sample jsonp content"/>
  <json:property name="content" escapeXml="false">
      <h2>heading 2</h2>

    <table border="1" cellspacing="0" style=" width: 576px; height: 46px;" cellpadding="0">
    <tr>
    <td width="20%">&#160;header 1</td>
    <td width="20%">&#160;header 2</td>
    <td width="20%">&#160;header 3</td>
    <td width="20%">&#160;</td>
    <td width="20%">&#160;</td>
    </tr>
   
    <tr>
    <td width="20%">&#160;1 x 1</td>
    <td width="20%">&#160;1 x 2</td>
    <td width="20%">&#160;</td>
    <td width="20%">&#160;</td>
    <td width="20%">&#160;</td>
    </tr>
   
    <tr>
    <td width="20%">&#160;</td>
    <td width="20%">&#160;</td>
    <td width="20%">&#160;2 x 3</td>
    <td width="20%">&#160;</td>
    <td width="20%">&#160;</td>
    </tr>
   
    <tr>
    <td style=" height: -11px;" width="20%">&#160;</td>
    <td style=" height: -11px;" width="20%">&#160;</td>
    <td style=" height: -11px;" width="20%">&#160;</td>
    <td style=" height: -11px;" width="20%">&#160;</td>
    <td style=" height: -11px;" width="20%">&#160;4 x 4</td>
    </tr>
    </table>
   
    <p>&#160;</p>
   
    <h3>heading 3</h3>
   
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque at nisi id erat congue fringilla. Aenean urna purus, pharetra sit amet bibendum eget, pellentesque non ligula. Nulla quis mi lectus. Cras aliquet nisi et dui mollis vel commodo est ultricies. Aenean eget magna quis turpis sollicitudin viverra. Vestibulum vulputate lectus semper nulla semper dignissim luctus ante elementum. Proin nibh arcu, venenatis eget bibendum sit amet, imperdiet volutpat eros. Sed tellus odio, malesuada sed adipiscing vitae, sodales quis turpis. Donec congue odio ac elit auctor blandit semper nunc posuere. Vivamus ac nibh id metus sagittis porta eget vel leo. Donec sed tincidunt tortor. Nam eget ipsum est, quis scelerisque diam. Nam rutrum sagittis diam, ut malesuada felis gravida sed. Mauris gravida laoreet magna, id hendrerit enim condimentum id. </p>
   
    <hr color="00cc33" size="1" />
    <p>&#160;</p>   
  </json:property> 
</json:object>)

As you can see, the json-taglib is doing the heavy lifting for us, escaping html for use in javascript, creating the json objects.  To make this valid jsonp for use with jQuery, we are just prefixing the json with the callback param value, and wrapping the json response in parenthesis.  Easy enough, right?

References:
http://api.jquery.com/jQuery.ajax/
http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/
http://api.jquery.com/jQuery.getJSON/
http://json-taglib.sourceforge.net/tagreference.html

0 comments

Add a comment

Please provide your name, email address (won't be published) and a comment

About

David Malone is a Java developer residing in the Twin Cities area.  He has been developing enterprise applications since 2004.  This is his personal blog, as well as his design and development workspace.