【问题标题】:Dynamically populate listview in jQuery mobile based on if file exists on phone根据手机上是否存在文件,在 jQuery Mobile 中动态填充列表视图
【发布时间】:2015-04-01 19:16:05
【问题描述】:

这是我的代码的开始。它只是从 JSON 文件中填充一个无序列表。我尝试使用 Cordova FileReader 没有任何运气。

document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
    alert("Got deviceready");

    var reader = new FileReader();
    var fileSource = cordova.file.externalDataDirectory;

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

            $.each( data, function( key, val ) {

            var $li = $("<li><a href='#'>"+val.title+"</a></li>");

            reader.onloadend = function(evt) {

                if(evt.target.result == null) {
                $li.find("a").on("click", function(){ downloadPdf(val.title,val.url); });
                } else {
                $li.find("a").on("click", function(){ openPdf(val.title); });
                }
            };

            // We are going to check if the file exists
            reader.readAsDataURL(fileSource + val.title + ".pdf");

            $("#linkList").append($li);
            $("#linkList").listview('refresh');
            });

    });


}

如您所见,此示例使用downloadPdf(title, url) 函数添加列表项。如果确实存在,我希望列表项改为调用函数openPdf(title)。文件保存在cordova.file.externalDataDirectory + title + ".pdf"

此代码不会将任何项目添加到我的列表中。

【问题讨论】:

    标签: javascript android jquery cordova jquery-mobile


    【解决方案1】:

    您可以使用file plugin 来检查文件是否存在

    var reader = new FileReader();
    var fileSource = <here is your file path>
    
    reader.onloadend = function(evt) {
    
        if(evt.target.result == null) {
           // If you receive a null value the file doesn't exists
        } else {
            // Otherwise the file exists
        }         
    };
    
    // We are going to check if the file exists
    reader.readAsDataURL(fileSource); 
    

    【讨论】:

    • 我曾尝试使用 FileReader,但没有成功。用我的代码更新了问题。
    • 我猜你的文件路径不正确。 fileSource + val.title + ".pdf" 我想文件名前应该有一个斜杠/。请向fileSource + val.title + ".pdf" 发送警报并检查您收到的内容。还要通过文件管理器检查文件是否确实存在于显示的路径目录中。 @janlindso
    • 不,添加斜线会产生双斜线。我现在尝试了一个警报,它返回了正确的路径,我可以看到:file:///storage/emulated/0/Android/data/com.helloworld/title.pdf
    • 我已经尝试做一些研究,我认为存在一些安全问题,不允许应用从 URL 读取文件。
    猜你喜欢
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 2016-09-30
    • 1970-01-01
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多