【问题标题】:WinJS reading local .json filesWinJS 读取本地 .json 文件
【发布时间】:2015-07-21 11:48:05
【问题描述】:

我正在尝试加载本地 .json 文件,以便可以与我的 javascript 一起使用。我试过这个解决方案:WinJS loading local json file

当我在 parsedObject 所在的位置插入任何变量时,我不断收到错误消息。我尝试了很多不同的解决方案,但似乎都没有奏效。

【问题讨论】:

  • 能否展示您的代码,尤其是在您尝试修改对象的地方
  • 我还没有为此编写任何代码 =/ 由于链接代码不起作用,我完全不知道该怎么做。抱歉...自动完成显示您可以使用命名空间 Windows.Data.Json,这就是我现在要寻找的。​​span>
  • 您尝试加载的文件是在您的包中(在您的项目中)还是其他地方?
  • 它们在我的项目中。我有一个名为 data 的文件夹,里面有 .json。
  • 您链接到的答案中的代码是您最好的起点。您不需要使用 Windows.Data.Json,因为 JS 具有内置的 JSON.* API(Windows.Data.Json,适用于没有固有支持的 C#、VB 和 C++ 应用程序。)并遵循乔恩,你需要展示你尝试过的所有代码,并指出它在哪里不起作用。这将帮助我们弄清楚发生了什么。同时,查看文件访问示例作为开始:code.msdn.microsoft.com/windowsapps/File-access-sample-d723e597

标签: json winjs


【解决方案1】:

通过将响应类型设置为“json”,可以通过 XHR 检索 JSON 文件。这种方式结果将是 JSON 对象。下面以sn-p为例:

<script>
        // Set url
        var jsonUrl = 'myJson.json';

        // Call WinJS.xhr to retrieve a json file
        WinJS.xhr({
            url: jsonUrl,
            responseType: "json"
            // https://msdn.microsoft.com/en-us/library/windows/apps/br229787.aspx
            // json: The type of response is String. This is used to represent JSON strings. responseText is also of type String, and responseXML is undefined.
            // Note  As of Windows 10, when responseType is set to json, the responseText is not accessible and the response is a JavaScript object. Behavior on Windows 8.1 and earlier remains as described above.
        }).done(

            // When the result has completed, check the status.
            function completed(result) {
                if (result.status === 200) {

                    // Get the XML document from the results.
                    console.log(result);
                    var jsonFileContent = result.response; // returns an object
                    console.log(jsonFileContent);
                    console.log(jsonFileContent.rabbits[0].name);

                    /* The content of file: myJson.json
                    {
                        "rabbits":[
                            {"name":"Jack", "age":3},
                            {"name":"Mac", "age":4},
                            {"name":"Hanna", "age":2}
                        ]
                    }
                    */
                }
            });
    </script>

【讨论】:

    猜你喜欢
    • 2012-09-12
    • 2019-05-29
    • 2018-06-25
    • 2017-07-07
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    相关资源
    最近更新 更多