正如评论所指出的,您将要进行 AJAX 调用 - 如果不从服务器获取文件,您将无法获取文件。我不确定您是否会坚持每次都进行 AJAX 调用。但是,使用 HTML5 文件系统可以防止您每次都重新获取 XML。
下面的代码/我的答案是在文件存在时在本地获取文件,并在本地不存在时从服务器获取文件,您的代码将如下所示(或非常相似的内容 - 我复制并粘贴了很多工作代码并试图抽象一些组件):
获取 xml 文件的函数调用,
无论是在本地还是从服务器,请参见下面的代码 - 确保fs
在进行以下调用之前已初始化,这是通过onInitFs
在请求文件系统函数中将其设置为您调用的全局变量来完成的
getFile("productinfo.xml",function(textDataFromFile){
console.log("some callback function"}
//your ... code should be handled here
);
从服务器获取文件的 AJAX 调用
function obtainFileFromServer(filename,callback){
var xhr2 = new XMLHttpRequest();
xhr2.onload = function(e){
writeToFile(filename,xhr2.response,callback);
}
xhr2.open('GET', "path/to/"+filename, true);
xhr2.send();
}
从 HTML5 文件系统中读取。
function getFile(filename,callback){
fs.root.getFile(filename, {create:false}, function(fileEntry) {
fileEntry.file(function(file) {
var errorHandler2 = function(e){
switch(e.name){
case "NotFoundError":
//if the productinfo.xml is not found, then go get it from the server
//In you're callback you'll want to also recall the getFile
obtainFileFromServer(function(){getFile(filename,callback);});
break;
default:
console.log(e);
break;
}
}
var reader = new FileReader();
reader.onloadend = function(e) {
callback(this.result);
};
reader.readAsText(file);
}, errorHandler2);
}, errorHandler);
}
写入 HTML5 文件系统
有两种方法可以查看 write 方法writeToFile()
(该文件 - 因此它首先发生的原因)。这似乎超出了这个问题的范围。我包括要截断的代码,但不包括用于确定是否需要重新下载示例/如果它是旧的示例的逻辑。
function writeToFile(filename,data,callback){
fs.root.getFile(filename, {create: true}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwriteend = function(e) {
//we've truncated the file, now write the data
writer.onwriteend = function(e){
callback();
}
var blob = new Blob([data]);
writer.write(blob);
};
writer.truncate(0);
}, errorHandler);
}, errorHandler);
}