簡體   English   中英

從 windows 小工具中的 JSON 文件檢索數據時出現問題

[英]Problem retrieving data from JSON file in windows gadget

我正在嘗試使用 jquery 訪問存儲在 JSON 文件(與小工具相同的文件夾中)中的數據。 以下示例在 firefox 和 Internet Explorer 中都可以正常工作(顯示“成功”),但作為小工具它不起作用(顯示“失敗”)。

$('#gadgetContent').html("fail");

$.getJSON("test.json", function(data) {

    $('#gadgetContent').html("success");
});

關於我做錯了什么的任何想法? 謝謝。

更新:

$.ajax({
    url: "test.json",
    dataType: 'json',
    error: jsonError,
    success: jsonSuccess
});

function jsonError(jqXHR, textStatus, errorThrown) {

    // As a gadget this function is called
    // jqXHR.readyState is 4
    // jqXHR.status is 0
    // jqXHR.responseText is undefined
}

function jsonSuccess(data) {
    // Browsers reach here
}

您應該像文本一樣閱讀文件,然后將其轉換為 json。 該實用程序應該可以幫助您:

    function getJsonFromFile(fileName) {
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        if (fso.FileExists(fileName)) {
                var f = fso.OpenTextFile(fileName, 1);
                var jsonStr = "";
                while (!f.AtEndOfStream) {
                    jsonStr += f.ReadLine();
                }
                f.Close();
        }

        return jQuery.parseJSON(jsonStr);
    }

請記住使用完整路徑調用它,例如:

var gadgetPath = System.Gadget.path;
var jsonFile = gadgetPath + "\\" + "foo.json";

var json = getJsonFromFile(jsonFile);

windows 小工具安全沙箱限制,將干擾 ajax 的工作方式。 When you pass a url to ajax call, it trid to make an HTTP request to that url, and incase of a browser the url does exist in the form of (file://localpath), but with a windows gadgets things are a bit不同,即從 window.location 派生的相對 url 不能用作 window ZA8CFDE63331BD59EB2AC96F8 此處不存在。

這里最簡單的方法是簡單地將 json 放在 JS 文件中並使用腳本標簽引用它,因為 HTML DOM 的那部分由處理渲染/加載內容的 sidebar.exe 代碼處理。

謝謝

尼拉吉

從原始帖子的評論中復制,這似乎提供了一個合適的解決方法。

我懷疑問題是 Windows 小部件缺乏對.json 文件類型的支持。 作為一種解決方法,我建議您將 JavaScript object 設置為 a.js 文件中的一個變量,然后使用getScript檢索並執行該 JavaScript。

這樣做之后,該變量應該可以在全局命名空間中訪問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM