I am trying out jQuery 1.6.4 with mobile to get a simple json feed and display it as a learning exercise. I can’t get the callback in the getJSON to fire though. The json feed is open and public so that’s fine. Could this be a jQuery 1.6.4 + mobile issue?
$.getJSON('https://raw.github.com/currencybot/open-exchange-rates/master/latest.json',
function (data) {
var items = [];
$.each(data, function (key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
You can’t do an AJAX request to this URL because it would violate the same origin policy. See http://e-mats.org/2010/01/jquery-getjson-and-the-same-origin-policy/ for an explanation. Here’s a quote:
Basically, regular AJAX uses XMLHtmlRequest, which has same-domain security policies in place. JSONP, on the other hand, inserts a script tag (without same-domain origin policies) that runs a callback function. But the end server has to support this since it is responsible for actually generating the script with the callback function.
If the server supports JSONP, you can do this by adding
callback=?to the request parameters in the url you call with getJSON. But it doesn’t look like this endpoint supports JSONP (addingcallback=?does nothing).So you will probably have to create a proxy endpoint on your server to access this data. Basically, create an endpoint on your own server that loads that data using whatever method makes sense (curl, etc..) and returns it exactly as-is. Then you can use regular AJAX to call your own server endpoint (same server = does not violate the same origin policy).