json文件中读取javascript

json文件中读取javascript

本文介绍了如何从.json文件中读取javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的脚本目前看起来像这样:

My script currently looks like this:

<script type="text/javascript">
  function updateMe(){
    var x = 0;
    var jsonstr = '{"date":"July 4th", "event":"Independence Day"}';
    var activity=JSON.parse(jsonstr);
    while(x<10){
    date = document.getElementById("date"+x).innerHTML = activity.date;
    event = document.getElementById("event"+x).innerHTML = activity.event;
    x++;
    }
  }
</script>

其中日期x和事件x是一系列html标签。此功能在页面加载(onload)时运行。我的目标是完成同样的事情,只能从本地.json文件,而不是我上面的硬编码。我已经查看了。

Where date"x" and event"x" are a series of html tags. This function runs when the page loads (onload). My goal is to do this exact same thing, only from a local .json file as opposed to the hard code that I've got above. I've already checked out http://api.jquery.com/jQuery.getJSON/.

本地.json文件如下所示:

The local .json file looks like this:

{"date":"July 4th", "event":"Independence Day"}

有任何建议吗?

推荐答案

当你说.json文件时,假设你的意思是在本地文件系统上存档。

Assuming you mean "file on a local filesystem" when you say .json file.

您需要保存格式为jsonp的json数据,并使用 file:// url 来访问它。

You'll need to save the json data formatted as jsonp, and use a file:// url to access it.

您的HTML将如下所示:

Your HTML will look like this:

<script src="file://c:\\data\\activity.jsonp"></script>
<script type="text/javascript">
  function updateMe(){
    var x = 0;
    var activity=jsonstr;
    foreach (i in activity) {
        date = document.getElementById(i.date).innerHTML = activity.date;
        event = document.getElementById(i.event).innerHTML = activity.event;
    }
  }
</script>

文件c:\ data \ activity.jsonp包含以下行:

And the file c:\data\activity.jsonp contains the following line:

jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];

这篇关于如何从.json文件中读取javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:11