jQuery Tutorial Tutorials - jQuery jQuery.getJSON()

jQuery jQuery.getJSON()

The jQuery.getJSON() method in jQuery is used to load json-encoded data from from the server using a get HTTP request. This is a shorthand Ajax get function which is equivalent to:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

jQuery jQuery.getJSON() syntax

jQuery.getJSON( url [, data ] [, success ] )
Parameter Type Description
url String request url
data PlainObject,String The data sent to the server
success Function callback function that is executed if the request succeeds.

jQuery jQuery.getJSON() example

example

chain multiple .done(), .always(), and .fail() callbacks on a single request

var jqxhr = $.getJSON( "example.json", function() {
  console.log( "success" );
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });
 
// Perform other work here ...
 
// Set another completion function for the request above
jqxhr.complete(function() {
  console.log( "second complete" );
});

example

Load the JSON data from test.php and access the stat and data from the returned JSON data.

Server side - PHP

<?php
    $data = array(
        "stat" => "success",
        "data" => array(
            "name" => "lautturi",
            "website" => "lautturi.com",
        )
    );
    
    echo json_encode($data);
?>

Browser side - jQuery

$.getJSON( "/res/test/ajax/json.php", function( json ) {
    console.log(json);
    console.log(json.stat); //success
    console.log(json.data);
    console.log(json.data.name); // lautturi
});

jQuery jQuery.getJSON() example

Try now

Date:2019-08-30 02:57:15 From:www.Lautturi.com author:Lautturi