Thursday, December 10, 2009



Here i will show you how jsonp works.
Let's first dive into details and then later we gonna see an example on jsonp.


"JSONP" stands for JavaScirpt Object Notations with Padding.
we already know JSON is one of the data formats used on web.
and we also know that AJAX doesn't allow us to fetch data from cross-Domain sites.
(here Ajax is Browser's Native Object and not RIA's Object).
ofcourse it's possible with RIA controls on Browser like Silverlight, Flash using policy files.

For work-around solution to this restriction, JSONP comes into the scene.
JSONP is not a new technology, it's a simple idea, (just like AJAX,) it uses existing technologies.
JSONP is used for data fetching (in JSON Format) from cross-Domain and same-Domain sites using
"javascript" tag's "src" attribute.

After data has been received, it calls a callback function, which is padded to the URL value of "src" attribute.
Confused? see the example below.


JSONP vulnerable to cross site scripting attacks (XSS).
so don't use it for sensitive data fetching.
and use it with trusted sites only.


In this example, i will show you how to fetch data from same-Domain site using
>create a new project and name it 'TestSite" and open it.
>create a new folder called "jsonp".
>create a new html file under jsonp folder, and name it "jsonp.html"
>and write this code in it.

<script type="text/javascript">
function callme(obj)
txt.value="value one:"+obj.two[0];
txt.value+=" value two:"+obj.two[1];
txt.value+=" ";
txt.value+="Obj one val:";
testing jsonp! <i>callback function should be defined first, then get jsonp using javascript src.</i><br/>
<textarea id="txt" cols="20" rows="4">
<script type="text/javascript" src="http://localhost:1049/TestSite/JsonP/Handler.ashx?jsonp=callme">

Now create an handler file under jsonp folder, and name it, "jsonp.ashx"

using System;
using System.Web;

public class Handler : IHttpHandler
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/javascript";
string callbackFuncName=context.Request.QueryString["jsonp"].ToString();
string json = "{'one':'rozyrojz','two':[1,2]}";
public bool IsReusable {
get { return false; }

Now run the jsonp.html. That's it!


Thanks for reading!