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.
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.
$(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.
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.