Displaying list data from a RESTful web service (Javascript)
There is more than one way to display a list of data (e.g. tasks, contacts, messages, meetings, etc) from a RESTful web service. There are pros and cons to each. Here is an example that uses pure Javascript (e.g. no jQuery, no JS frameworks).
- The Front-end developer may propose writing a factory (or service) to retrieve the data (via HTTP get/post), parse the results and instantiate a list of objects from those results. The example below is problematic because it is hardcoded to bootstrap CSS and creates a shadow DOM. This type of code is generally difficult to maintain and should be used for demo purposes only.
function loadContacts() {
var xmlhttp = new XMLHttpRequest();
var contactList = [];
xmlhttp.open('GET', 'https://SOME_URL/Contacts.json', true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
contactList = JSON.parse(xmlhttp.responseText);
}
for (var i = 0; i < contactList.length; i++) {
var obj = contactList[i];
var email = "<div class=col-md-3>" + obj.EmailAddress + "</div>";
var fullname = "<div class=col-md-3>" + obj.Fullname + "</div>";
var id = "<div class=col-md-3>" + obj.Id + "</div>";
var dob = "<div class=col-md-3>" + obj.DateOfBirth + "</div>";
document.getElementById("contactsRoot").innerHTML += "<div class=row>" + id + fullname + email + dob + "</div>";
}
}
};
xmlhttp.send(null);
} - The HTML is very simply in this case. The loadContacts() method from the <body> tag is called after the page has been loaded (as defined by the event attribute “onLoad”. The script
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<meta name="google" value="notranslate">
<title></title>
<link rel='stylesheet prefetch' href='//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>
</head>
<body>
<html>
<body onLoad="loadContacts()">
<div id="contactsRoot" class="container"></div>
<script>INSERT JAVACRIPT CODE HERE</script>
</body>
</html>