data = {"items": [
{
"title": "sample 1",
"author": "author 1"
},
{
"title": "sdample 2",
"author": "author 2"
}
]};
这是我的 json 文件。
现在我想在我的js中读取这个本地json文件以在HTML页面中打印json的值 我不想使用任何 httpsRequest。
注意:我没有使用任何网络服务器
下面是我的JS文件
function data(languageClass){
var news = document.getElementsByClassName(languageClass)[0];
var item = json.items;// where json is local json copy which i want
console.log( "hiiii" + item);
for(var i = 0; i < item.length; i++) {
var h5 = document.createElement("h5");
h5.innerHTML = item[i].title;
news.appendChild(h5);
var p = document.createElement("p");
p.innerHTML = item[i].author;
news.appendChild(p);
}
}
下面是我的 HTML 文件:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="D:/Shubhankar/web/quess.json"></script>
<script type="text/javascript"
src="../web/Question.js"></script>
<title>Java Interview Question</title>
<link rel="icon" type="image/png" href="../img/icon.png">
</head>
<body onload='data("interviewQuestions")'>
<div class="interviewQuestions"></div>
</body>
</html>
最佳答案
data = {"items": [
{
"title": "sample 1",
"author": "author 1"
},
{
"title": "sdample 2",
"author": "author 2"
}
]};
这不是有效的 JSON。
如果没有 Web 服务器或 XHR 请求,您将无法加载数据。在应用程序中获取此数据的一种方法是拥有一个包含 JSON 内容的 JS 文件。 示例:
var data={"items": [
{
"title": "sample 1",
"author": "author 1"
},
{
"title": "sdample 2",
"author": "author 2"
}
]
}
现在使用script
调用这个JS文件标签。
<script src="path/to/jsonfile.js"></script>
关于javascript - 我正在开发一个网站,我想在我的 js 文件中本地读取一些 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43914561/