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>

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文件如下所示:

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

Any suggestions?

推荐答案

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

您需要将格式化为JSONP的json数据保存,并使用file:// url进行访问.

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>

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

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

Json相关问答推荐

PostgreSQL 12.17从JSON数组提取元素

将数组中的值作为键连接到另一个数组中的值(Jolt)

NoneType 对象的 Python 类型错误

如何使用jq按键 Select 并获取整个json输出来更改json中的多个值

如何将属性拆分为嵌套的JSON内容?

使用jq根据对象中键的值查找对象

使用 jolt 将对象数组转换为数组

如何使用nifi从json文件中过滤属性

PowerShell:如何将哈希表输出为 json 并使用 foreach 循环将其存储在变量中?

如何将从嵌套 Select 返回的空值转换为空数组?

如何在golang中获取 struct 的json字段名称?

为什么我不能在 C# 中引用 System.Runtime.Serialization.Json

如何使用 jq 将 JSON 对象流转换为数组

使用 jq 从 bash 中管道分隔的键和值创建 JSON

Spring Security 和 JSON 身份验证

在自定义 JsonConverter 的 ReadJson 方法中处理空对象

ASP.NET Core API 仅返回列表的第一个结果

在 Java 中比较两个 JSON 文件的最佳方法

如何在 Python 中合并两个 json 字符串?

如何从 MySQL 中检索 JSON 数据?