0

Why is the getJSON function structured this way?

 $.getJSON( url [, data ] [, success ] )

Instead of just returning an object, i.e.:

 var myjson = $.getJSON( url [, data ])
DogBot
  • 528
  • 1
  • 6
  • 15
  • 3
    One word: Asynchronous. The variable cannot be assigned a value, as the response will be coming later. While waiting for that, any code below that line will keep executing. When the data is received, your callback (success handler) will execute. – blex Jul 14 '15 at 20:43
  • your `myjson` is actually a promise object. For a detailed answer see [how-to-return-the-response-from-an-asynchronous-call](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – charlietfl Jul 14 '15 at 20:45
  • 1
    Wow- Now I understand the principle/need behind a promise object too! Thanks. - Also Thanks Blex I get it. If not done that way I might use the variable before it is ready. Thank you. – DogBot Jul 14 '15 at 20:51
  • I am sorry this question got down-voted. Several of us where wondering and researching it. It was a case of not seeing the forest for the trees...Asynchronous!! DUH!! ----- ALSO: HOW DO I MARK THIS SOLVED BTW? – DogBot Jul 14 '15 at 20:55
  • I don't know why this was downvoted, it's an extremely good beginner question. – jnovack Jul 14 '15 at 20:59

1 Answers1

-1

Because it returns a jqXHR object that contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible. Basically, how would you know if the request was successful?

RobertoNovelo
  • 3,347
  • 3
  • 21
  • 32