简体   繁体   中英

Problem retrieving data from JSON file in windows gadget

I am trying to access data stored in a JSON file (in the same folder as the gadget) using jquery. The following example works fine in both firefox and internet explorer (shows "success"), but as a gadget it doesn't work (shows "fail").

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

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

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

Any ideas as to what I'm doing wrong? Thanks.

UPDATE:

$.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
}

You should read the file like text and then convert it to json. This utility should help you:

    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);
    }

Remember to call it with full path like:

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

var json = getJsonFromFile(jsonFile);

The windows gadgets security sandbox restrictions, will be interfering with the way ajax works. 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 different, ie the relative url which is derived from window.location cannot be used as the window object does not exist here.

The easiest here would be to simply put the json in a JS file and refer it using the script tag, as that part of the HTML DOM is taken care of by the sidebar.exe code which takes care of rendering/loading stuff.

Thanks

Neeraj

Duplicate from the comments on the original post, which seemed to provide a suitable work-around.

I suspect the problem is that the Windows Widget lacks support for.json file types. As a work-around, I suggest that you set your JavaScript object to a variable inside of a.js file and use getScript to retrieve and execute that JavaScript.

After doing so, that variable should be accessible in the global namespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM