JQuery: the $.getJson method

Published Wed, Aug 19 2009 11:44

In the previous post, we’ve met the $.get and $.post methods. At the time, we’ve seen how we could easily load a JSON payload returned from the server. If you know that you’ll be getting JSON and that the request will be an HTTP GET, then you can use the $.getJson utility function instead of the $.get function.

To illustrate its use, we’re going to reuse the previous example and we’ll only be updating the client code of the page:

<script type="text/javascript">
    $(function() {
        $("input[type=button]").click( 
            function(){
                $.getJSON("HowdyHandler.ashx", 
                      { name: $("input[type=text]").val()},
                      function(data){
                        $("div").html("Hi <b>" + data.name + "</b>" );
                     } );
            });
    
    });
</script>

As you can see, the only difference is that the $.getJSON function receives only three parameters (when compared with the code we had to receive JSON with the $.get function). This isn’t surprising because this method reuses the $.get method internally for doing its work. Here’s its current implementation:

getJSON: function( url, data, callback ) {
    return jQuery.get(url, data, callback, "json");
}

And that’s it for today. Keep tuned for more on JQuery.

Filed under:

Leave a Comment

(required) 
(required) 
(optional)
(required)