data.json file code :
{"Roll":"101","name": "Sona", "city": "Australia"}
HTML Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Girfa : Json Tutorial Read Data From Server File</title>
<script language="javascript">
function readData(){
var data_file = "data.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("Your browser broke!");
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("data").innerHTML ="<b>Roll : </b>" + jsonObj.Roll + "<br><b>Name : </b> " + jsonObj.name + "<br><b>City : </b>" + jsonObj.city;
//document.getElementById("data").innerHTML ="<br><b>City : </b>" + jsonObj.city;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
</head>
<body>
<h1 align="center">Data Fetch From Server Example</h1><hr />
<input type="button" value="Get Data" onclick="readData()" />
<div id="data"></div>
</body>
</html>
No comments:
Post a Comment