2012-10-07 25 views
2

我有一個小的HTML5(使用jQuery手機)網絡應用程序,它可以緩存文件以脫機使用它們,但是有些部分在離線時似乎不工作。HTML5離線JSON不起作用

這些文件被緩存好(我可以在Web檢查器中看到它們),但是當我嘗試訪問使用jQuery加載JSON文件的頁面時,它無法加載。

我試着創建一個空的函數來加載JSON文件(當索引頁被加載時),看看這是否會有所幫助,但它似乎沒有區別。

以下是不想脫機工作的功能。

我的問題是:它應該脫機工作還是我錯過了什麼?

// events page listing start 
function listEvents(data){ 
$.getJSON('/files/events.json', {type: "json"},function (data) { 
     var output = ''; 
      for (i in data) 
       { 
       var headline = data[i].headline; 
       var excerpt = data[i].rawtext; 
       output += '<div id="eventsList">'; 
       output += '<h3>'+headline+'</h3>'; 
       output += '<p>'+ excerpt +'<p>'; 
       output += '</div>'; 
       } 
      $("#eventsPageList").html(output).trigger("create"); 
     }); 
} 

回答

1

我不是很確定,如果我對此有理。但我認爲,當你離線時,ajax請求總會失敗。它不會使用本地緩存文件。你應該嘗試的是將數據緩存在localStorage中。當ajax請求失敗時,回退到localStorage。

0

確定這裏有一個似乎可以工作的版本,我讀取json文件並將它放在localstorage中,然後在listEvents函數中使用localstorage。

頁面加載時我調用這個函數來添加JSON來localStorage的

function cacheJson(data){ 
     $.getJSON('/files/events.json', 
       {type: "json", cache: true},function (data) { 
      localStorage['events'] = JSON.stringify(data); }); 
    } 

那麼這個函數輸出JSON(從localStorage的)到頁面,與其他如櫃面localStorage的不包含json。

function listEvents(data){ 

    if (localStorage.getItem("events") === null) { 
     var output = ''; 
     output += 'Sorry we have an error'; 
     $("#eventsPageList").html(output).trigger("create"); 
    } 
    else { 
    data = JSON.parse(localStorage['events']); 
     var output = ''; 
     for (i in data) 
      { 
      var headline = data[i].headline; 
      var excerpt = data[i].rawtext; 
      output += '<div id="eventsList">'; 
      output += '<h3>'+headline+'</h3>'; 
      output += '<p>'+ excerpt +'<p>'; 
      output += '</div>'; 
      } 
     $("#eventsPageList").html(output).trigger("create"); 
    } 
} 

它似乎工作正常,但我錯過的東西,可能會導致問題?

有沒有更有效的方法來做到這一點?