2015-07-21 85 views
0

我试图加载本地上传.json文件,以便我可以用我的JavaScript中使用。我试过这个解决方案:WinJS loading local json fileWinJS读取本地上传.json文件

当我在parsedObject所在的位置插入任何变量时,我总是收到一个错误。我尝试了很多不同的解决方案,但似乎没有任何工作。

+0

你能证明你的代码,尤其是当你试图修改的对象 –

+0

我没有写的一行代码为尚未= /自联代码不工作,我完全没有想过该怎么做。对不起......自动完成表明,你可以使用命名空间Windows.Data.Json,这就是我想要找了。 –

+0

是你想在你包加载(在您的项目)或其他somwhere的文件吗? –

回答

0

JSON文件可以通过XHR通过设置响应类型为“JSON”进行检索。这样的结果将是JSON对象。下面是代码片段为例:

<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>