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