Is it possible to fetch JSON data using JavaScript without relying on jQuery? I am only interested in retrieving data using pure JavaScript.
Here is an example of my JSON file:
{"JsonProjectIDResult":[{"_capacity":15,"_description":"Meeting Room","_dev_default_view":3,"_deviceID":1,"_deviceName":"MobiTech","_deviceTypeID":1,"_projectID":1,"_roomID":2,"_roomName":"Room2","_room_admin_mail":null}]}
This is what my home.html file looks like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8>
<title>JavaScript Get Json</title>
</head>
<body>
<h1>My Home Page</h1>
<div id="results">
<!-- Display Jason Data -->
</div>
<script>
var resultDiv = document.getElementById("results");
var newsURL = "http://localhost:81/testjs/data.json";
var req;
if (window.XMLHttpRequest) {
// code for modern browsers
req = new XMLHttpRequest();
} else {
// code for old IE browsers
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.onreadystatechange = function() {
var html = "";
if (req.readyState == 4 && req.status == 200) {
var response = JSON.parse(req.responseText);
if(typeof(req.responseText)==="string") {
dataVar = req.responseText;
} else {
if (typeof(req.responseXML)==="object") {
dataVar = req.responseXML;
};
}
var myData = response['JsonProjectIDResult'];
//Print results
html += myData[0]._capacity+"<br />";
html += myData[0]._description+"<br />";
html += myData[0]._dev_default_view+"<br />";
html += myData[0]._deviceID+"<br />";
html += myData[0]._deviceName+"<br />";
html += myData[0]._deviceTypeID+"<br />";
html += myData[0]._projectID+"<br />";
html += myData[0]._roomID+"<br />";
html += myData[0]._roomName+"<br />";
html += myData[0]._room_admin_mail+"<br />";
resultDiv.innerHTML = html;
}
};
req.open("GET", newsURL, true);
req.send();
</script>
</body>
</html>
After receiving some helpful advice from friends, I have modified my code accordingly and now it works as expected. Next, I am looking to iterate through the records using a loop. Is it possible to achieve this using JavaScript?