Question 2 part 2

mail@pastecode.io avatar
unknown
html
a year ago
2.0 kB
7
Indexable
Never
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Question 2</title>
</head>
<body>
	<button onclick="makeAjaxQuery()">Get Car service repository</button>
	<div id="display"></div>

	<script type="text/javascript">
		function makeAjaxQuery(){
			var xhttp = new XMLHttpRequest();
			xhttp.onreadystatechange = function(){
				readyStateChangeHandler(xhttp);
			};

			xhttp.open("GET", "question2.json", true);
			xhttp.send();
		}

		function readyStateChangeHandler(xhttp){
			if (xhttp.readyState == 4){
				if(xhttp.status == 200){
					handleStatusSuccess(xhttp);
				} else{
					handleStatusFailure(xhttp);
				}
			}
		}

		function handleStatusFailure(xhttp){
			var display = document.getElementById("display");
			display.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
		}

		function handleStatusSuccess(xhttp){
			var jsonText = xhttp.responseText;
			var carObj = JSON.parse(jsonText);
			displayRepository(carObj);
			console.log(carObj);
		}

		function displayRepository(carObj) {
			var html = "";

			html += "<h3> <u> Car service repository </u> </h3>";
			html += "<p> <i> <b> Car Service Station: </b>" + carObj.station + "</i> <br /> <br />";

			for(var i = 0; i < carObj.carList.length; i++) {
				var carListObj = carObj.carList[i];

				html += "<b> Car plate: </b>" + carListObj.plate + "<br />";
				html += "<b> Model: </b>" + carListObj.model + "<br />";
				html += "<b> Year: </b>" + carListObj.year + "<br />";
				html += "<b> Service Card: </b>";

				for (var j = 0; j < carListObj.serviceCardList.length; j++) {
					var serviceListObj = carListObj.serviceCardList[j];

					html += "<ul> <li>" + serviceListObj.date + ", service " + serviceListObj.service + "</li> </ul>";
				}

				html += "<br /></p>";
			}

			var display = document.getElementById("display");
			display.innerHTML = html;
		}
	</script>
</body>
</html>