经过数周的研究,我决定使用Phonegap的File API来更新我的应用程序。在Phonegap Google Group上,我发现我必须执行以下步骤:
我已经执行了第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>
答案 0 :(得分:2)
我对Phonegap文件Api有很多问题和挫折感,因此决定制作一个简单的API来处理它。我的API发布在这里:
https://github.com/poja/PhoneGap-FileAPI-Improved
希望它有所帮助。