Search code examples
javascriptjsonjsonpgetjson

Get json list hosted on gihub - doesn't push into html


I'm trying to pull a content from a json file which is hosted on external server, into html. Here is what I have so far but no success.

    var myurl = "https://gist.github.com/Keeguon/2310008/raw/865a58f59b9db2157413e7d3d949914dbf5a237d/countries.json";
$(document).ready(function () {
    $.getJSON(myurl,
    function (json) {
        var tr;
        for (var i = 0; i < json.length; i++) {
            tr = $('<tr/>');
            tr.append("<td>" + json[i].name + "</td>");
            tr.append("<td>" + json[i].code + "</td>");
            $('table').append(tr);
        }
    });
});

Any help will be much appreciated!


Solution

  • You have two problems:

    1. You're trying to make a cross-domain AJAX request which is not allowed under the same origin policy.
    2. The "JSON" you're trying to load is not valid JSON.

    I'd recommend using the Github API here along with a JSONP request. I'd also recommend using this fork of the gist you linked to. With that in mind:

    $.ajax({
        url: 'https://api.github.com/gists/7748738',
        dataType: 'jsonp',
        success: function (response) {
            var countriesStr = response.data.files['countries.json'].content
                , countries = JSON.parse(countriesStr);
    
            // countries is an array of countries.
        }
    });
    

    Example: http://jsfiddle.net/WUAKu/1/