2015-07-21 86 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>