简体   繁体   中英

$.getJSON not working for a local file in Cordova

I have a basic app written in Cordova that is trying to fetch a local JSON file held in the www/menus subdirectory of the app. My Javascript code looks like this:

function loadMenuJSON() {
    var jsonPath = "../menus/" + menuc + ".json";
    $.getJSON(jsonFile, function(result) {
        alert("Received JSON.");
        sortAllergies(result);
    });
}

When I attempt to alert outside of the getJSON statement, it works fine, but the "Received JSON" alert doesn't appear, meaning it didn't receive the object. I've removed the header from the HTML file that blocks requests, and specified in my config.xml that the app should allow all requests to any addresses. My problem only occurs on Android and iOS, not when I build it to browser.

EDIT: I've also been having problems when trying to debug, because I can't access the Javascript console on an Android emulator.

After doing further research, I learned that Cordova build on Android will usually expect references to JS files from an odd absolute path. What you can do is replace your path with one that refers absolutely to the app filesystem, like so:

var path = window.location.href.replace('index.html', '');
var jsonFile = path + "menus/" + menuc + ".json";
$.getJSON(jsonFile, function(result) {
    sortAllergies(result);
});

You'll want to replace index.html with the name of the HTML file you're calling the JS from, eg. menus.html .

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