javascript - 我正在开发一个网站,我想在我的 js 文件中本地读取一些 json 文件

标签 javascript html

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/

相关文章:

javascript - Elasticsearch | "data"参数必须是字符串、TypedArray 或 DataView 类型之一

javascript - 在 Javascript 中按降序对字符串进行排序(最有效)?

javascript - Chrome 扩展程序 : add image to DOM

html - 在输入元素上叠加一个 div

html - Iphone 6 或 Ios 8 safari 图像随机重复问题

javascript - 缩放网页时出现问题

javascript - JS : How to track click on links without losing the back button

html - 浏览器会在同一个页面上多次加载一个 css 文件吗?

php - 将标题保留在动态网站上

Javascript 改变 Css 元素