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

时间:2017-05-11 11:47:20

标签: 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);
	}
		
		
}
&#13;
&#13;
&#13;

下面是我的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>

1 个答案:

答案 0 :(得分:3)

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>