Ian Vink
Ian Vink

Reputation: 68810

jquery: Ajax Json simple rendering

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');
    });

Upvotes: 2

Views: 496

Answers (1)

Ben Lee
Ben Lee

Reputation: 53349

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:

When creating a simple mash-up with data from external sources, you usually want to read the data in a suitable format – such as JSON. The tool for the job tends to be javascript, running in your favourite browser. The only problem is that requests made with XHR (XMLHttpRequest) has to follow the same origin policy, meaning that the request cannot be made for a resource living on another host than the host serving the original request.

To get around this clients usually use JSONP – or a simple modification of the usual JSON output. The data is still JSON, but the output also includes a simple callback at the end of the request, triggering a javascript in the local browser. This way the creator of the data actually tells the browser (in so many hacky ways) that it’s OK, I’ve actually thought this through. Help yourself.

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 (adding callback=? 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).

Upvotes: 3

Related Questions