Home > Uncategorized > Load Cross Domain JSON via JSONP Proxy

Load Cross Domain JSON via JSONP Proxy

A well known security constraint on modern browsers, is that AJAX requests can only be made to the server which served the page. To get around this, you can use CORS for modern browsers, or JSONP.

JSONP, however does require that the data provider wraps their JSON response in a function call, which they may not do. Therefore, an easy solution is to create a proxy that wraps JSON in a function call, such as:

public partial class JsonProxy : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string link = Request.QueryString[“url”];
if (link == null || link == “”)
{
Response.Write(“Requires url parameter”);
return;
}
WebClient wc = new WebClient();
string strJson = wc.DownloadString(link);
Response.Write(“jsonp_callback(” + strJson + “);”);
}
}

Then, on the client side, a this can be used as follows (JQuery version):

<html>
<head>
<script type=”text/javascript” src=”jquery.js”></script>
<script language=”javascript”>
$(init)
function init()
{
LoadJson(“http://www.bbc.co.uk/tv/programmes/genres/comedy/schedules/upcoming.json&#8221;);
}

function jsonp_callback(data)
{
$(“body”).html(“Found ” + data.broadcasts.length + ” upcoming comedy shows”);
}

function LoadJson(url)
{
var s = document.createElement(“script”);
s.type = “text/javascript”;
s.src = “http://www.yourwebsite.com/jsonproxy.aspx?url=&#8221; + url;
$(“head”).append(s);
}
</script>
</head>
<body>
Please Wait.
</body>
</html>

 

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: