jQuery Get Json

.getJSON() 等於用 'json'資料類型的 .ajax()
$.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
});
範例Ajax getJSON
範例程式碼 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>汽車銷售報表</div>
    <div id="div381"></div>
    <button id="btn382" type="button">點我載入汽車銷售報表 (json type)</button>    
    &nbsp;<a href="/backend/data/car-sale.json" target="_blank">原始銷售報表</a>
</div>




comments powered by Disqus