javascript 在Phonegap中读取本地文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14812866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read local file in Phonegap
提问by shadow_of__soul
I'm trying to read a local file in Phonegap to load the language strings for the application and I can't make it work :(
我正在尝试读取 Phonegap 中的本地文件以加载应用程序的语言字符串,但无法使其正常工作:(
The code is pretty straightforward:
代码非常简单:
var pathToLocalFile = "/home/user/android/assets/www/js/";
var langCache = new FileReader();
langCache.onload = function(data){
col = JSON.parse(data);
refreshAllStrings();
};
langCache.onerror = function(err){
debug.error(err);
};
langCache.readAsText(pathToLocalFile+currentLang+'.json');
This code doesn't work on the Ripple emulator and I replaced it with
此代码在 Ripple 模拟器上不起作用,我将其替换为
var pathToLocalFile = "file:///android_asset/www/js/";
in case of android, with the same result:
在 android 的情况下,结果相同:
Uncaught TypeError: Object #<Console> has no method 'warning' cordova-2.4.0.js:2616
initRead cordova-2.4.0.js:2616
FileReader.readAsText cordova-2.4.0.js:2660
loadLanguage
In the Ripple emulator, I started Chrome with google-chrome -–allow-file-access-from-files
and the Android config and manifest has all the permissions for and the plugins set.
在 Ripple 模拟器中,我启动了 Chrome,google-chrome -–allow-file-access-from-files
Android 配置和清单具有所有权限和插件集。
Of course I'm missing something, but any idea what this could be?
当然,我错过了一些东西,但知道这可能是什么吗?
Regards.
问候。
采纳答案by codemonkey
If the file is under the www folder of your app you don't need to add '/home/..' or 'file:///'. You should just be able to load the contents using an "AJAX" fetch even though it is bundled in the app.
如果文件位于应用程序的 www 文件夹下,则无需添加“/home/..”或“file:///”。即使它捆绑在应用程序中,您也应该能够使用“AJAX”获取加载内容。
$.get('js/filename.ext');
回答by Nick Williams
The error you're seeing is actually a result of cordova-2.4.0.js calling a non-existent "warning" method. It should be console.warn. It is attempting to warn you that using a string for the readAsText method is now deprecated, and that you should use a File reference instead.
您看到的错误实际上是cordova-2.4.0.js 调用不存在的“警告”方法的结果。它应该是console.warn。它试图警告您,现在不推荐使用字符串作为 readAsText 方法,您应该改用 File 引用。
What should be happening is a console.warn of "Using a string argument with FileReader.readAs functions is deprecated."
应该发生的是“不推荐使用带有 FileReader.readAs 函数的字符串参数”的 console.warn。