Search code examples
javascriptjqueryjsonajaxgetjson

How to read content of a JSON file in jQuery


I am trying to get information from an API. Basically I have a URL that returns a JSON data, and I will just need to use it.

var url = "http://212.18.63.135:9034/played?sid=1&type=json";
$.getJSON(url, function(data) {
    console.log(data)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The above is my code, and it does not work. This is an API that provides live data, so I am not sure if I can use ajax instead...

Any idea how to make it work?

UPDATE:

I updated the URL, and now it gives Access-Control-Allow-Origin error. I had a look at other question related to CORS and they all suggest to make configuration in the server side as much as I understood. But I am not looking into fixing the CORS error, I am just looking for a solution to access these JSON data.

So I hope it does not get duplicated as my point is different in this question.


Solution

  • You can do this way.

    Adding callback=? to your URL turned your request to JSONP, so no CORS

    More information about getJSON and JSONP.

    If you interested how JSONP works you can read that article

    var url = "http://212.18.63.135:9034/played?sid=1&type=json&callback=?";
    $.getJSON(url, function(data) {
        console.log(data)
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>