javascript - 在 html 中读取 JSON
问题描述
我想要做的应该很简单,但不知何故我就是不让它工作?
所以我有以下 JSON 文件 jsonFile.json
:
{
"level1":"elemet1",
"level2":"element2",
"level3":{
"testing":"element3"
}
}
我想访问其中的数据,使用像这样的 HTML 页面index.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>JSON Example</title>
</head>
<body>
<div id="data1">Level 1 value : </div>
<div id="data2">Level 2 value : </div>
<div id="data3">Level 3 value : </div>
<script>
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'jsonFile.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
function init() {
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
for (var key in actual_JSON) {
var innerkey = actual_JSON[key];
for (var inner in innerkey) {
document.getElementById('data1').innerHTML += 'Level 1 value'+innerkey[inner]['level1']+'<br>';
document.getElementById('data2').innerHTML += 'Level 2 value: '+innerkey[inner]['level2']+'<br>';
document.getElementById('data2').innerHTML += 'Level 3 value: '+innerkey[inner]['level3']+'<br>';
}
}
});
}
init();
</script>
</body>
</html>
因此从浏览器直接调用“index.html”会产生以下错误:
Access to XMLHttpRequest at 'file:///C:/Users/Engine/Documents/JSON_TEST/jsonFile.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, brave, https.
loadJSON @ index.html:31
为了解决它,我现在正在使用node.js
服务器app.js
:
var http = require('http');
var fs =require('fs');
var server = http.createServer(function(req,res){
console.log('request was made : '+req.url);
res.writeHead(200,{'Content-Type':'text/html'});
var myReadStream = fs.createReadStream(__dirname +'/index.html','utf8');
myReadStream.pipe(res);
});
server.listen('3000','127.0.0.1');
console.log('listening to 3000');
所以现在调用app.js
using :
node app.js
并调用地址:127.0.0.1:3000
这是我得到的错误:
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at (index):38
at XMLHttpRequest.xobj.onreadystatechange ((index):28)
再说一次,我想它应该很简单,但我只是不知道我在这里缺少什么!提前感谢您的帮助!
解决方案
index.html
问题是无论用户请求的 URL是什么,您总是会返回。尝试http://localhost:3000/jsonFile.json
在浏览器中打开:您将看到 HTML 文件的内容,而不是预期的 json。
让我用你自己的代码来证明我的观点:
var server = http.createServer(function(req,res){
console.log('request was made : '+req.url);
var myReadStream;
// If the user requests the json file...
if (req.url.endsWith('jsonFile.json')) {
// ...get the json file, NOT the index.html
myReadStream = fs.createReadStream(__dirname +'/jsonFile.json', 'utf8');
} else {
myReadStream = fs.createReadStream(__dirname +'/index.html', 'utf8');
}
res.writeHead(200,{'Content-Type':'text/html'});
myReadStream.pipe(res);
});
有更好的方法来创建这个服务器。看看http-server。
修复此问题后,您将不得不查看您的 javascript 循环,但该变量actual_JSON
将包含 JSON 文件的内容。