英文:
I can’t display the data from the json file on the html page
问题
Script.js和test.json位于'public'文件夹中。我需要在HTML页面中显示test.json中的数据。
script.js:
$(document).ready(function() {
let qqq = 'test.json';
let www = JSON.parse(qqq);
document.getElementById("eee").innerHTML = www;
});
server.js:
var express = require("express");
var path = require("path");
var app = express();
app.get("/", function(req, res) {
res.sendFile(__dirname + "/views/index.html");
});
app.use(express.static(path.join(__dirname, "public")));
app.listen(8008);
console.log("服务器已启动!");
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>报告</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="red" id="eee"></div>
</body>
</html>
test.json:
{"tests": [
{ "testName": "testname1",
"value": "test_value",},
{ "testName": "testname2",
"value": "test_value",}
] }
英文:
Script.js and test.json are located in the 'public' folder. I need to display data from test.json in the html page.
script.js:
$(document).ready(function() {
let qqq = 'test.json';
let www = JSON.parse(qqq);
document.getElementById("eee").innerHTML = www;
});
server.js:
var express = require("express");
var path = require("path");
var app = express();
app.get("/", function(req, res) {
res.sendFile(__dirname + "/views/index.html");
});
app.use(express.static(path.join(__dirname, "public")));
app.listen(8008);
console.log("Server has started!");
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Report</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"
></script>
<script src="script.js"></script>
</head>
<body>
<div class="red" id="eee"></div>
</body>
</html>
test.json:
{"tests": [
{ "testName": "testname1",
"value": "test_value",},
{ "testName": "testname2",
"value": "test_value",}
] }
答案1
得分: 2
let qqq = 'test.json'; // 正在解析 test.json 字符串。
您可以使用以下方式通过 ajax 从 json 文件中获取数据:
$.ajax({
type: "GET",
url: "test.json",
dataType: "json",
success: function(data) {
let www = JSON.parse(data);
$("#eee").html(www);
},
error: function(){
alert("json 文件未找到");
}
});
英文:
let qqq = 'test.json'; //you are parsing test.json string.
you can use ajax to get data from json file as following
$.ajax({
type: "Get",
url: "test.json",
dataType: "json",
success: function(data) {
let www = JSON.parse(data);
$("#eee").html(www);
},
error: function(){
alert("json not found");
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论