0

I am working with the openweather API and after looking at sample code, I sometimes will see API calls made such as this:

function getWeather(callback) {
    var weather = 'http://api.openweathermap.org/data/2.5/forecast?lat=51.5072&lon=0.1275&units=metric';
    $.ajax({
      dataType: "jsonp",
      url: weather,
      success: callback
    });
}

But then occasionally I will see requests made using this method:

function gettingJSON(){
document.write("jquery loaded");
$.getJSON("api.openweathermap.org/data/2.5/weather?q=London&APPID=ee6596241130f193adf1ba90e625cc10",function(json){
document.write(json);
}

What is the main difference between these methods and is one considered better or more efficient than the other?

Andy
  • 275
  • 2
  • 14
  • Sometimes the data is not a JSON object – Bálint Jul 23 '16 at 16:37
  • Duplicate of [Difference Between $.getJSON() and $.ajax() in jQuery](http://stackoverflow.com/questions/1076013/difference-between-getjson-and-ajax-in-jquery) – Bálint Jul 23 '16 at 16:38
  • @Bálint I read that one and it did not explain which should be used and when. Specifically if data is JSON (like from Openweather API), is there a reason to use $.ajax or just go to $.getJSON – Andy Jul 23 '16 at 16:39
  • Then see this one: http://stackoverflow.com/questions/2887209/what-are-the-differences-between-json-and-jsonp It's a duplicaze either way – Bálint Jul 23 '16 at 16:42

1 Answers1

0

$.getJSON is a shortcut for $.ajax passing a dataType 'json' and a method 'GET'. Using $.ajax you can use other methods, like 'POST' or 'PUT' and other data types, like 'xml' or 'html'.

In your first example, the datatype is 'jsonp', it is another thing a little bit different... Is when you pass a function name X, and the response is the json wrapped by this function name... X({...}) it is useful when you need to call a web api from another domain, because ajax call must be in the same domain, but <script> tags can have a src attribute pointing to another domain.

lmcarreiro
  • 5,312
  • 7
  • 36
  • 63