0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah ah thank you, I was guessing that might be it, but I'm used to php determining arguments by order supplied it threw me off. This is great

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.