<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File API</title>
<link rel="stylesheet" href="style.css">
<script>
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function(e) {
JsonObj = JSON.parse(e.target.result);
fileDisplayArea.innerHTML = e.target.result;
}
reader.readAsText(file);
});
}
</script>
</head>
<body>
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<h1>Cricketer Details</h1>
<table class = "table">
<tr>
<th>Name</th>
<th>Country</th>
</tr>
<tr>
<td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td>
</tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON()">Update Details </button>
</div>
</body>
</html>
在此能够在html中显示Json文件。但我想根据Json文件中的值更新某些值。怎么做?
我想要类似下面的内容。 应使用上传的json文件的值更新html Page值。例如,应根据json文件更新示例名称和国家/地区。怎么做那个绑定?
<h1>Cricketer Details</h1>
<table class = "table">
<tr>
<th>Name</th>
<th>Country</th>
</tr>
<tr>
<td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td>
</tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON()">Update Details </button>
</div>
Myjson
{
"name": "XXXX",
"country": "India",
}
任何人都请告诉我如何修改它以显示json数据。非常感谢!
答案 0 :(得分:0)
<html>
<body>
<form id="jsonFile" name="jsonFile" enctype="multipart/form-data" method="post">
<fieldset>
<h4>Upload Json File</h4>
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</fieldset>
</form>
<script type="text/javascript">
function loadFile() {
var input, file, fr;
if (typeof window.FileReader !== 'function') {
alert("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText(e) {
lines = e.target.result;
var newArr = JSON.parse(lines);
document.getElementById("Name").innerHTML = newArr.name;
document.getElementById("Country").innerHTML = newArr.country;
}
}
</script>
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
</body>
</html>