JSONP Callback Support

CallbackMethods support serving of JSONP results. All you have to do is add a querystring parameter of callback or jsonp to the request string followed by a value of the callback that is called on the page:

http://localhost/JsonStockService.ashx?Method=GetStockQuote&Symbol=msft
&HelloWorld&callback=onCallback

The callback (or jsop) parameter triggers the JSONP result which looks like this:

onCallback( {"Symbol":"GLD",
"Company":"SPDR Gold Trust",
"OpenPrice":0,
"LastPrice":134.75,
"NetChange":0.00,
"LastQuoteTime":"2011-01-05T02:00:00Z",
"LastQuoteTimeString":"Jan 4, 4:00PM"} );

Let's look at this in more detail.

What is JSONP?

JSONP allows for cross domain callbacks from a server using a GET operation. Basically JSONP allows supplying a URL that handles the request and a query string parameter that identifies the callback method that is to be called when the script returns the value. Behind the scenes JSONP gets around the XSS limitations for XMLHTTP by embedding a new script tag into the page and executing the code it returns which amounts to a function call into your page code with the result value from the JSONP function as a parameter.

CallbackMethods do JSONP

The Web Toolkit CallbackHandler implementation supports server side JSONP callbacks through standard CallbackMethods. You can basically call any method in a CallbackHandler marked with the [CallbackMethod] attribute via JSONP.

For example to call a CallbackMethod:

public class JsonStockService : CallbackHandler
{
        [CallbackMethod]
        public StockQuote GetStockQuote(string symbol)
        {
            StockServer stocks = new StockServer();
            return stocks.GetStockQuote(symbol);
        }
}

you can use the following url:

*http://localhost/mywebapp/JsonStockService.ashx?Method=GetStockQuote&Symbol=msft&HelloWorld&callback=onCallback

The key is the callback query string parameter which triggers the handler to return a JSONP response. You can use either callback or jsonp as the parameter name.

If you now load this above URL as a < script> link it will execute this function and pass the JSON into it and effectively eval it.

Using JSONP with jQuery.getJSON

An easy way to call the JSONP Url is to use jQuery's $.getJSON() method which automatically creates a callback parameter when passing a callback=? querystring parameter to the server. The following example returns a stock quote from the server as an object:

$(document).ready( function() {
	$(document).ready( function() {
		$.getJSON("http://localhost/myWebApp/JsonStockService.ashx?callback=?",
                  {method: "GetStockQuote", symbol: "msft" },
                  function(result) {
                    alert(result.Company);
                  });
	});

in this case jQuery generates a URL like this:

http://localhost/WestWindWebToolkitWeb/Ajax/StockPortfolio/ JsonStockService.ashx?callback=jsonp1294220650933&method=GetStockQuote&symbol=gld

which results in a response like this:

jsonp1294220650933( {"Symbol":"GLD",
"Company":"SPDR Gold Trust",
"OpenPrice":0,
"LastPrice":134.75,
"NetChange":0.00,
"LastQuoteTime":"2011-01-05T02:00:00Z",
"LastQuoteTimeString":"Jan 4, 4:00PM"} );

jQuery automatically creates a handler function that is called in response to this particular callback and simply calls the specified method with the result value. Easy right?

Notice that callback=? MUST BE specified in the URL explicitly and cannot be added to the parameter map in the second parameter that generates the key value pairs for the query string. It's what jQuery uses internally to identify a JSONP callback.

Using JSONP Callbacks without a CallbackHandler

JSONP request parsing and request parsing in general can also be handled 'manually' within any code by using the JsonCallbackMethodProcessor class which handles all aspects of request parsing and JSON/JSONP generation.

For example the following code can be used to create an ASPX page that handles JSON and JSONP callbacks without any special controls on the page:

public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var method = Request.QueryString["Method"];
            if (!string.IsNullOrEmpty(method))
            {
                var processor = new JsonCallbackMethodProcessor();
                processor.ProcessCallbackMethodCall(this);  // pass in instance that containse CallbackMethods
            }
        }

        [CallbackMethod]
        public string HelloWorld()
        {
            string name = HttpContext.Current.Request.QueryString["Name"];
            return string.Format("Hello World {0}. Time is: {1}", name,DateTime.Now);
        }
    }

The key is a routing method that checks for a specific Method querystring parameter and then processes the request accordingly.

See also

Using CallbackHandler with GET Requests

© West Wind Technologies, 1996-2015 • Updated: 12/19/15
Comment or report problem with topic