[英]How to read local Storage JSON in angular index.html file and show in View page source as a script
[英]How to read JSON file and add the values to HTML page
编辑:
我只需要一种简单的方法来读取 html 页面中的 json 文件,是否可以不使这个复杂化? 我应该能够在 html 页面中的任何地方获得关键参考,没有任何限制。
结尾
I have html page that hosted on the heroku app and I'm trying to read the json file and display the values of json file to the html page, how would I do that?
这是我到目前为止所尝试的。
我的学生 JSON 文件:
{
name: 'John Doe',
car: 'BMW X5'
}
我的 HTML 页面:
<html>
<header>
const fs = require('fs');
let rawdata = fs.readFileSync('student.json');
let student = JSON.parse(rawdata);
console.log(student);
console.log('my Name: ' + student.name);
console.log('my Name: ' + student.car);
</header>
<body>
<h1>My Name is: <%=name%> </h1>
<p>My Car is: <%=car%></p>
</body>
</html>
有多种方法可以将本地 JSON 文件加载到 web 页面中,但只有几种首选方法可以显示加载的数据。
加载数据后,明智的做法是利用数据绑定或模板来呈现数据。
// Data from load var student = { name: 'John Doe', car: 'BMW X5' }; var StudentViewModel = function(studentData) { this.name = ko.observable(studentData.name); this.car = ko.observable(studentData.car); } ko.applyBindings(new StudentViewModel(student));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <h1>My Name is: <span data-bind="text: name"></span></h1> <p>My Car is: <span data-bind="text: car"></span></p>
// Data from load var student = { name: 'John Doe', car: 'BMW X5' }; window.addEventListener('DOMContentLoaded', (event) => { let templateHtml = document.getElementById('student-template').innerHTML; let StudentTemplate = Handlebars.compile(templateHtml); document.body.insertAdjacentHTML('beforeend', StudentTemplate(student)); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.4.2/handlebars.min.js"></script> <script id="student-template" type="text/x-handlebars-template"> <h1>My Name is: {{name}}</span></h1> <p>My Car is: {{car}}</span></p> </script>
您必须添加脚本标签。
<html>
<header>
<script>
const fs = require('fs');
let rawdata = fs.readFileSync('student.json');
let student = JSON.parse(rawdata);
console.log(student);
console.log('my Name: ' + student.name);
console.log('my Name: ' + student.car);
document.getElementById("print-name").innerHTML = `My Name is: ${student.name}`;
document.getElementById("print-car").innerHTML = `My Name is: ${student.car}`;
</script>
</header>
<body>
<h1 id="print-name"></h1>
<p id="print-car"></p>
</body>
</html>
有两种方法可以将数据从服务器显示到客户端:
1) 您可以更改您的客户端 JS 代码以发出 http 请求以获取 JSON,然后动态更新 HTML。 优点:简单,缺点:附加 http 请求。
2) 或者您可以在服务器上编辑 HTML。 优点:避免了 http 请求,缺点:稍微复杂一些。
服务器节点代码:
const http = require('http');
const myJson = require('student.json', 'utf-8');
let myHtml = require('fs').readFileSync('index.html', 'utf-8');
myHtml = myHtml.replace(/<%=(\w*)%>/, (_, key) => myJson[key]);
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(myHtml);
}).listen(8080);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.