我对 Javascript 和 JSON 相当陌生,我正在尝试访问未命名 JSON 数组中的值。由于这不是我的 JSON 文件,因此我无法更改它并为数组指定名称。 这是 JSON 代码:
[
{
"address":"0x51c3",
"Balance":"2425"
},{
"address":"0x51c9",
"Balance":"2425"
}
]
这是我在 Javascript/AJAX 方面所做的尝试:
<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>
最佳答案
您的 etherBalance 在 JSON 中称为 Balance,在 DIV ID 中也称为 Balance。
现在插入工作了
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>
关于javascript - 无法使用 Javascript 访问未命名 JSON 数组中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32509831/