I am fairly new to Javascript and JSON and I am trying to access the values in an unnamed JSON array. Since this is not my JSON file, I cannot alter it and give the array a name. Here is the JSON Code:
[
{
"address":"0x51c3",
"Balance":"2425"
},{
"address":"0x51c9",
"Balance":"2425"
}
]
Here is what I have attempted on the Javascript/AJAX front :
<html>
<head>
<meta content = "text/html; charset = ISO-8859-1" http-equiv = "content-type">
<script type = "application/javascript">
function loadJSON(){
var data_file = "http://localhost/balance.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("Address").innerHTML = jsonObj[1].address;
document.getElementById("Balance").innerHTML = jsonObj[1].Balance;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
</head>
<body>
<table class = "src">
<tr><th>Address</th><th>Balance</th></tr>
<tr><td><div id = "Address"></div></td>
<td><div id = "Balance"></div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON()">Update Details </button>
</div>
</body>
</html>
Your etherBalance is called Balance in the JSON and Balance in the DIV ID too.
Now the insertion works
var data = '[ { "address":"0x51c3", "Balance":"2425" },{ "address":"0x51c9", "Balance":"2425" }]'; function loadJSON() { var jsonObj = JSON.parse(data); // jsonObj variable now contains the data structure and can // be accessed as jsonObj.name and jsonObj.country. document.getElementById("Address").innerHTML = jsonObj[1].address; document.getElementById("Balance").innerHTML = jsonObj[1].Balance; }
<table class="src"> <tr> <th>Address</th> <th>Balance</th> </tr> <tr> <td> <div id="Address"></div> </td> <td> <div id="Balance"></div> </td> </tr> </table> <div class="central"> <button type="button" onclick="loadJSON()">Update Details</button> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.