【问题标题】:PhoneGap: File API - loading json data on click eventPhoneGap:文件 API - 在点击事件上加载 json 数据
【发布时间】:2013-02-26 21:05:02
【问题描述】:

我已经实现了从设备上的外部文件加载 json 数据的代码。程序应该是这样工作的:在点击事件首先它会尝试查看本地存储文件(course.txt),如果它存在,读取并显示它(标题列表)。

HTML 代码:

<div data-role="page" id="page1">
    <a href="#page2" onclick="courseList()">Load Course</a></div>
</div>
<div data-role="page" id="page2">
    <p id="text" align="center"></p>
    <div id="print"></div>
</div>

JS代码:

jsonString = '';
function courseList() {
    readWriteFile();
    var myData = JSON.parse(jsonString);
    if (myData != '' || myData != undefined) {
        var $list = $('#print');
        $.each(myData, function(i, item) {
            $list.html(item.title);
        });​
    } else {
        document.getElementById('text').innerHTML = 'No data in storage';
    }
}

function readWriteFile() {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess, onFSError);
}
function onFSSuccess(fileSystem) {
    fileSystem.root.getFile("course.txt", {create:true, exclusive:false}, gotFileEntry, onFSError);
}
//FileReader Cordova API
function gotFileEntry(fileEntry) {
    fileEntry.file(gotFile, onFSError);
}
function gotFile(file) {
    readAsText(file);
}
function readAsText(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("Read as text");
        console.log(evt.target.result);
    };
    reader.readAsText(file);
    jsonString = reader.readAsText(file);
}
function onFSError(err) {
    console.log(err.code);
}

考虑到上述过程,结果为空。我无法发现我的错误。任何帮助将不胜感激。

【问题讨论】:

  • 您是否收到任何错误日志?
  • var myData = JSON.pars(jsonString) - jsonString='' - 你解析一个空变量吗?
  • @dan 不,我不是在解析一个空变量...jsonString 是一个全局变量,它在整个过程的顶部声明,然后在成功访问文件后我' m 将读取结果应用到它jsonString = reader.readAsText(file); 就是这样。
  • 我认为问题在于对文件的访问是异步完成的。这意味着解释器到达 jsonString = reader.readAsText(file);当 phonegap 仍在访问存储中的数据时线路。

标签: jquery json cordova filereader


【解决方案1】:

试试这个

function readAsText(file) {
  var reader = new FileReader();
  //asnycrhonous task has finished, fire the event:
  reader.onloadend = function(evt) {
    console.log("Read as text");
    console.log(evt.target.result);
    //assign the data to the global var
    jsonString = evt.target.result
    //keep working with jsonString here
  };
  reader.readAsText(file);    
}

【讨论】:

    【解决方案2】:

    这是因为文件读取是异步发生的。 在 onloadend 中添加您的 readAsText

    尝试添加这个:

    function readAsText(file) {
        var reader = new FileReader();
        reader.onloadend = function(evt) {
            console.log("Read as text");
            console.log(evt.target.result);
            reader.readAsText(file);
            jsonString = reader.readAsText(file);
        };   
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2019-04-14
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多