2015-12-13 18 views
0

我正在開發一個帶有HTML5和Javascript的Windows 10應用程序。在windows 10 html5應用中讀取json文件?

在代碼的一部分,我需要從位於項目文件夾中的json文件中獲取數據。我在下面嘗試,但它似乎並沒有工作。

try 
{ 
    $.getJSON('../js/towards_beach.json', function (data) 
    { 
     document.getElementById("Result").innerText = "We are working on it"; 
    }); 
} 
catch(err) 
{ 
    document.getElementById("Result").innerText = err; 
} 

有沒有人有線索我怎麼能做到這一點? 我需要在winjs中註冊這個函數嗎? enter image description here

+0

我不知道的平臺,但是你確定try/catch是如何處理WinJS中的Ajax錯誤的方法?這似乎不太可能,因爲Ajax調用是異步的。傳統上這是通過使用'error'回調來完成的 –

+0

我正在做一個js文件中的所有這些,我的問題不是關於try catch語句,而是問如何讀取json文件。任何方式感謝您的幫助,我會認爲你的觀點 –

+0

這看起來像它可能是在WinJS的方式? https://msdn.microsoft.com/en-us/library/windows/apps/br229787.aspx –

回答

3

如果使用jQuery的的要求去做正確的方法是:

var jqxhr = $.getJSON("example.json", function() { 
    console.log("success"); 
}).done(function() { 
    console.log("success"); 
}).fail(function() { 
    console.log("error"); 
}).always(function() { 
    console.log("complete"); 
}); 

文檔是在這裏http://api.jquery.com/jquery.getjson/

如果使用WinJS .xhr

WinJS.xhr({url:"example.json"}).done(
    function completed(request) { 
     console.log("success"); 
    }, 
    function error(request) { 
     console.log("error"); 
    }, 
    function progress(request) { 
     console.log("progress"); 
    }); 

doc在這裏https://msdn.microsoft.com/en-us/library/windows/apps/br229787.aspx

+0

謝謝@Mehdi我會試試這個 –

2

下面的代碼將幫助你閱讀JSON文件

var url = new Windows.Foundation.Uri("ms-appx:///data/data.json"); 
Windows.Storage.StorageFile.getFileFromApplicationUriAsync(url).then(function (file){ 

Windows.Storage.FileIO.readTextAsync(file).then(function (text) { 
    var parsedObject = JSON.parse(text); 
    // do something with object 
    }); 
}); 

將這個代碼的功能,無論你想:)快樂編碼