Gal Ratner
Gal Ratner is a Techie who lives and works in Los Angeles. Follow galratner on Twitter Google
JSONP the easy way with jQuery and a simple IHttpHandler

JSONP or “JSON with padding” is a slight variation of JSON. In JSON we create a string representation of a JavaScript object and call eval(myObject) in order for our script to read the data. We can then show the data in the object by simply looping over the fields or collections and adding the HTML to a div.


JSONP adds a little twist. It already includes the callback function. When we request a data from a remote server by dynamically including a script, the data coming back is already wrapped inside a JavaScript function call. When the call is completed and the script added to the HTML DOM the callback function is invoked by the result.
JSONP data looks like: jsonFeed({"title": "PJSON Data", "items": [{"FirstName":"John","LastName":"Smith"},{"FirstName":"Gregg","LastName":"Smith"}]});
When jsonFeed is the callback function.


In this blog post I will demonstrate the easiest and fastest way to create and consume JSONP data in ASP.NET. WCF includes JSON as one of the response formats it is capable of returning, however, in order to return JSONP you need to create a custom MessageEncoder. There is an example of how to do that here.
I opted out for a simpler solution and borrowed part of WCF. Let’s look at the code:
I am going to assume I want to display a list of people on the screen. A person class will look like this:

[DataContract]
public class Person
{
    [DataMember]
    public string FirstName { getset; }

    [DataMember]
    public string LastName { getset; }
}


Lets create a generic handler to return a list of Person

<%@ WebHandler Language="C#" Class="JSONPHandler" %>

using System;
using System.IO;
using System.Web;
using System.Collections.Generic;
using System.Runtime.Serialization.Json;

public class JSONPHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        List<Person> people = new List<Person>(){
            new Person(){ FirstName = "John", LastName="Smith"}, 
            new Person(){ FirstName = "Gregg", LastName="Smith"}
        };

        context.Response.Write(@"jsonFeed({""title"": ""JSONP Data"", ""items"": ");
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<Person>));
        ser.WriteObject(context.Response.OutputStream, people);
        context.Response.Write("});");
        context.Response.Flush();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Notice I used a DataContractJsonSerializer to serialize our list.
Now let’s utilize jQuery to pick up the data and add it to the HTML

<head>
    <title>test</title>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.getJSON("JSONPHandler.ashx?jsoncallback=?");
        });

        function jsonFeed(data) {
            $.each(data.items, function (i, item) {
                $("#people").append("<p>Name: " + item.FirstName + " " + item.LastName + "</p>"); 
            });
        }
    </script>
</head>
<body>
<div id="people"></div>
</body>

The result is a list of people we can access from any domain. Simple and quick.

Shout it


Posted 13 Dec 2010 1:28 AM by Gal Ratner
Filed under:

Powered by Community Server (Non-Commercial Edition), by Telligent Systems