javascript - 在html页面中读取Json“元素”
问题描述
说我有以下config.json文件:
{
"level1":{
"level1_1":{
"example": "test",
"example2":"123123"
},
"level1_2":{
"example": "test",
"example2":"123123"
}
},
"level2":{
"level2_1":{
"example": "test",
"example2":"123123"
},
"level2_2":{
"example": "test",
"example2":"123123"
}
}
}
我只是想阅读,说 html 文件中level2_2.example2的值,如下所示:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>reading json</title>
<style>
</style>
</head>
<body>
<br>
<div id="output">file value : </div>
<br>
<script>
// Starts.
init();
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'config.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);
// init(xobj.responseText)
}
};
xobj.send(null);
}
function init() {
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
// Transforms the JSON object into a readable string.
var json_string = JSON.stringify(actual_JSON, undefined, 2);
// Select <br> tag.
var output = document.querySelector("#output");
// Adds it to the DOM.
output.innerHTML += json_string;
});
}
</script>
</body>
直接调用 HTML 文件会产生以下错误:
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, brave, https.
所以我有以下 nodejs 脚本来运行服务器:
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');
调用地址传递比以下错误:
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at (index):40
at XMLHttpRequest.xobj.onreadystatechange ((index):29)
(anonymous) @ (index):40
xobj.onreadystatechange @ (index):29
XMLHttpRequest.send (async)
loadJSON @ (index):33
init @ (index):37
(anonymous) @ (index):20
所以这里的问题是;我在这里错过或不明白什么?我可以调用 json 文件中的特定元素吗?
解决方案
您的问题是 HTML 页面可能是通过 file:// 协议打开的,并且节点服务器在http://localhost:8080或类似这些行的地方运行。因此主机不一样。浏览器将阻止跨域请求(从一个主机到另一个主机的请求),除非目标响应特定的标头或主机相同。请记住,即使 HTML 文件和 API 都在同一主机上提供,但在不同的端口上,CORS 仍然会启动并且请求将被阻止。
在您的 Node 应用程序中,您可以在发送响应之前添加标头:
res.header("Access-Control-Allow-Origin", "*");
这将允许所有主机(所有来源)成功地向您的服务器发送请求,而不会被浏览器阻止。在生产环境中,您会希望它包含特定主机而不是通配符,但出于开发目的,这将允许您正常工作。
另一种可能性是从 Node 服务器的上下文中提供静态文件,以便 HTML 页面和 API 都驻留在同一主机下(localhost:8080 或任何您的情况)。届时,CORS 的问题将不存在。
推荐阅读
- apache-kafka - log4j 中的 kakfkaAppender 超时?
- microservices - JHipster 微服务集中化,不使用 Docker compose 或任何 Docker 容器,需要帮助
- unicode - 我应该使用哪种字体来显示所有汉字?
- pandas - 熊猫在乘法列上
- java - 使用 YUM 在 RHEL7 上 3 个不同的 Openjkds
- asp.net-core - SignalR HubContext 仅发送到一个客户端
- ios - UserNotifications related events
- c# - ASP.NET Core Razor 页面:将 html 内容写入新的浏览器选项卡?
- r - R:定义连续值的起始条件
- java - 显示整个文本后,是否可以使 TextView 选取框停止并反转?