$.getJSON()
AJAX - with .getJSON() - EasyProgramming.net
by Nazmus Nasir
HTML
<!-- Easy jQuery - Learn AJAX - how to use .getJSON() - #14 -->
<p>
Welcome to the 14th Easy jQuery Tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. This is similar to the $.get() method but it gives you very strict control over what kind of data your web page is expecting, JSON.
</p>
<p>
$.getJSON() example:</p>
<pre>
$.getJSON(url,data, successCallbacK);
</pre>
<p>
Notice that there is no 'datatype' argument here because type JSON is built in.
</p>
<p>
A full example would look something like this:
</p>
<pre>
$.getJSON(url,data, successCallbacK)
.done(function(){})
.fail(function(){})
.always(function(){});
</pre>
<p>
The example is pretty straight forward so let's practice below.
</p>
<h2>
Let's practice:
</h2>
<table id="heroesTable">
<thead>
<th>Name</th>
<th>Superhero Name</th>
<th>City</th>
</thead>
<tbody id="heroesBody"></tbody>
</table>
<br><br><br><br><br><br><br>
CSS
#heroesTable {
border: 1px solid #dddddd;
width: 100%;
margin-bottom: 20px;
}
JavaScript
$.getJSON('https://www.easyprogramming.net/heroes.json', function(data){
/* console.log(data); */
$(data).each(function(i, hero){
$('#heroesBody').append($("<tr>")
.append($("<td>").append(hero.name))
.append($("<td>").append(hero.superheroName))
.append($("<td>").append(hero.city)));
});
})
.done(function(){
alert("Completed");
})
.fail(function(e){
console.log('error:');
console.error(e);
})
.always(function(){
alert("always runs");
});