Gideon
Gideon

Reputation: 1886

Understanding the arguments for the getJSON() jquery method

I'm trying to understand the getJSON method in jquery.

Reading the documentation it states that it has the following arguments:

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

Where the data argument is addiotnal key, value pairs to be passed along with the request, and the success is a funtion with its own arguments (data, textStatus, jqXHR ).

Every time I see it used however, it seems as though the arguments for the original getJSON method ignore the 'data' argument, as here:

$.getJSON('/jquery/result.json', function(jd) {
         $('#stage').html('<p> Name: ' + jd.name + '</p>');
         $('#stage').append('<p>Age : ' + jd.age+ '</p>');
         $('#stage').append('<p> Sex: ' + jd.sex+ '</p>');
      });
  });

});

This is in the structure $.getJSON('URL', function(returned_data) {...}); right?

So how does the method know the second argument isn't the data argument, is it because on seeing a function it just assumes it is the 'success' argument?

Many thanks for your help.

Upvotes: 0

Views: 217

Answers (1)

Barmar
Barmar

Reputation: 780889

The brackets around the 2nd and 3rd arguments mean that they're optional.

jQuery figures out which arguments you supplied by looking at the type. If the second argument is an object, it's data. If it's a function, it's the success callback.

Lots of jQuery functions work like this. They're very flexible about which arguments you supply, using the types to infer which were left out.

Upvotes: 1

Related Questions