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”);
}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=” + url;
$(“head”).append(s);
}
</script>
</head>
<body>
Please Wait.
</body>
</html>