Search code examples
javascriptjqueryjsonjsonp

Working with a JSON on a third-part server


I'm developing an Android application with cordova, I need to read the json file from this address: Dati.venezia.it and put it into a json variable. i have tried using jQuery getJson but i had problems with CORS i have also tried the same think with JSONP but i havent got how it works. Any help would be appreciated.

console.log("start");
var url = 'http://dati.venezia.it/sites/default/files/dataset/opendata/livello.json?callback=?';
this.risultato= $.getJSON(url, function(data){

}); 
console.log("end");

and this was the attempt with getJson

$.getJSON('http://dati.venezia.it/sites/default/files/dataset/opendata/livello.json', function (data) {
  console.log(data);

  var items = data.items.map(function (item) {
    return item.key + ': ' + item.value;
  });

  showData.empty();

  if (items.length) {
    var content = '<li>' + items.join('</li><li>') + '</li>';
    var list = $('<ul />').html(content);
    showData.append(list);
  }
});

Solution

  • You are correct that you can use jsonp as a workaround. Looking at Dati.venezia.it , it doesn't look like it currently supports jsonp. You'll need to have the endpoint Dati.venezia.it provide a callback for jsonp to work.

    Additionally, the endpoint is missing the response header Access-Control-Allow-Origin, which won't allow other sites to pull data from it without that header. This is why you're running into CORS issues. If you have control of that website, you'll need to add Access-Control-Allow-Origin to it's response headers.