0

经过数周的研究,我决定使用 Phonegap 的 File API 来更新我的应用程序。在 Phonegap Google Group 上,我发现我必须执行以下步骤:

  1. 使用 XHR 加载此文件
  2. 将文件写入文件系统
  3. 检查互联网连接
  4. 如果是,请使用 FileTransfer 对象下载最新文件。
  5. 如果不是,请使用您的缓存文件

我已经完成了第 1 步,我的文件现在正在 XHR 中加载。现在我被困在第 2 步。我尝试了filewriter,但没有成功,而且关于 Phonegap 的 File API 的信息也不是很清楚。谁能帮我这个?

这是我的 XHR 脚本:

<script language="javascript" type="text/javascript">
function loadHome() {
    var request = new XMLHttpRequest();
    request.open("GET", "file:///sdcard/Download/home.json", true);
    request.onreadystatechange = function() {//Call a function when the state changes.
    if (request.readyState == 4) {
        if (request.status == 200 || request.status == 0) {

            var home = JSON.parse(request.responseText);
            var data = "<table cellspacing='0'>";
            for (i = 0; i < home.length; i++) {
                data += "<td>";
                data += "<a href='" + home[i].link + "'/>";
                data += "<img src='" + home[i].img + "'/>";
                data += "<div class='dsc'>" + home[i].expo + "<br><em>";
                data += home   [i].datum + "</em></div></a></td>";
            }
            data += "</table>";
            var twitter = document.getElementById("home2");
            twitter.innerHTML = data;
        }
    }
}
console.log("asking for home");
request.send();

</script>

这是我对文件编写器的第一次尝试:

<script type="text/javascript" charset="utf-8">

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}

function gotFS(fileSystem) {
    fileSystem.root.getFile("file:///sdcard/Download/home.json", {create: true, exclusive: false}, gotFileEntry, fail);
}

function gotFileEntry(fileEntry) {
    fileEntry.createWriter(gotFileWriter, fail);
}

function gotFileWriter(writer) {
    writer.onwriteend = function(evt) {
        console.log("contents of file now 'some sample text'");
        writer.truncate(11);  
        writer.onwriteend = function(evt) {
            console.log("contents of file now 'some sample'");
            writer.seek(4);
            writer.write(" different text");
            writer.onwriteend = function(evt){
                console.log("contents of file now 'some different text'");
            }
        };
    };
    writer.write("some sample text");
}

function fail(error) {
    console.log(error.code);
}

</script>
4

1 回答 1

2

我对 Phonegap File Api 有很多问题和挫败感,因此决定制作一个简单的 API 来处理它。我的 API 发布在这里:

https://github.com/poja/PhoneGap-FileAPI-Improved

希望能帮助到你。

于 2013-08-08T08:54:49.310 回答