I'm working on a basic AJAX code to show a JSON file stored locally using this HTML, but I keep getting an 'undefined' error. I'm opting for JavaScript instead of JQuery since I haven't delved into it yet; hoping my code is syntactically correct. Thanks in advance!
<script>
function loadJSON()
{
var data_file = "language.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Browser does not support this.");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("language").innerHTML = jsonObj.language;
document.getElementById("edition").innerHTML = jsonObj.edition;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
</head>
<body>
<table border="1">
<tr><th> language </th> <th> edition </th></tr>
<tr><td> <div id="language"></div> </td><td> <div id="edition"></div> </td> </tr>
</table>
<button type="button" onclick="loadJSON()"> Load JSON </button>
</body>
</html>
Here's the JSON content I want to showcase in a table via AJAX.
{
"books": [
{ "language": "Java" , "edition" :"second"},
{ "language": "C++" , "edition" :"fifth"},
{ "language": "C" , "edition" :"third"}
]
}