JSFiddle - React, Tailwind, and code Playground
HTML
<p>Counter: <span id="counter"></span></p>
<h1>Names</h1>
<div id="names"></div>
CSS
body {
font-family:Helvetica, Arial, sans-serif;
}
h1 {
font-size:150%;
font-weight:bold;
margin:10px 0 5px 0;
}
JavaScript
// this is just here so we can get jsfiddle
// to echo it back to us as a response
var jsonData = JSON.stringify({ "people" : [ { "id" : "jaubourg", "name" : "Julian Auborg" }, { "id" : "phiggins", "name" : "Peter Higgins" }, { "id" : "blowery", "name" : "Ben Lowery" }, { "id" : "jeresig", "name" : "John Resig" }, { "id" : "slightlylate", "name" : "Alex Russell" }, { "id" : "ajpiano", "name" : "Adam Sontag" } ] });
$(document).ready(function() {
// store the request object in a variable
// so we can do stuff with it later
var html,
names = $('#names'),
counter = $('#counter'),
tmpl = '<p>{{name}}</p>',
req = $.ajax('/echo/json/', {
data : { json : jsonData },
dataType : 'json',
type : 'POST'
// note that we could still pass
// success and error callbacks here,
// but there's no need to anymore
});
// add a callback ... later!
req.success(function(resp) {
counter.html(resp.people.length);
});
// add another callback, taking advantage
// of the fact that the object returned by
// $.ajax behaves like a promise
req.then(
// success
function(resp) {
var html = $.map(resp.people, function(p) {
return tmpl.replace('{{name}}', p.name);
}).join('');
names.html(html);
},
// error
function(jqXHR, responseText) {
console.log('things went badly');
names.empty();
}
);
});