jQuery Get Json

getJSON() is equivalent to a Ajax function with 'json' datatype
$.getJSON('car-sale-report.json', function() {
   //callback
});

//above is equivalent to below

$.ajax({
  url: url,
  dataType: 'json', //json data type
  data: data,
  success: callback,
  error: callback
});
ExampleAjax getJSON
Source Code Expand
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<!-- Javascript -->
<script type="text/javascript">
$(document).ready(function (){
    $("#btn382").click(function(){        
        /* set no cache */
        $.ajaxSetup({ cache: false });

        $.getJSON("/backend/data/car-sale.json", function(data){ 
            var html = [];

            /* loop through array */
            $.each(data, function(index, d){            
                html.push("Manufacturer : ", d.Manufacturer, ", ",
                          "Sold : ", d.Sold, ", ", 
                          "Month : ", d.Month, "<br>");
            });


            $("#div381").html(html.join('')).css("background-color", "orange");
        }).error(function(jqXHR, textStatus, errorThrown){ /* assign handler */
            /* alert(jqXHR.responseText) */
            alert("error occurred!");
        });
    });
});
</script>

<!-- HTML -->
<a name="#ajax-getjson-example"></a>
<div id="example-section38">    
    <div>Car sale report</div>
    <div id="div381"></div>
    <button id="btn382" type="button">Click to load car sale report (json type)</button>    
    &nbsp;<a href="/backend/data/car-sale.json" target="_blank">Original car sale report</a>
</div>




comments powered by Disqus