2013-01-23 21 views
0

我正在測試使用本地存儲的應用程序的概念,並且需要知道存儲它之後加載內容的最佳方式。從網絡存儲器加載HTML頁面

本質上,應用程序將預取內容,將其存儲在本地,然後根據請求將其存儲在新頁面中。我需要用戶能夠單擊一個鏈接(mysite.com/article1.html),而不是讓瀏覽器爲該頁面發出HTTP請求,只需加載本地存儲的HTML。

那麼如何加載「localNews」值而不是爲同一頁面創建HTTP?

var storeUrl; 
var localNews; 

$('a').click(function() { 
event.preventDefault(); 
storeUrl = $(this).attr('href'); 
$.ajax({ 
    url: storeUrl, 
    cache: true, 
    crossDomain: true 
}).done(function(html) { 
    localNews = html; 
    console.log(localNews); 
    localStorage.setItem('storeUrl', 'localNews'); 
}); 
}); 
+0

我認爲這個鏈接可能會阻止您重新創建存在的內容:http://www.html5rocks.com/en/tutorials/appcache/beginner/ –

+0

您忘記了$('a')中的事件click(function(事件){ – salexch

+0

@dystroy糾正我,如果我錯了,但這不會工作,如果我們使用PHP模板引擎 – HjalmarCarlson

回答

0
var storeUrl; 
    var localNews; 

    $('a').click(function(event) { 
     event.preventDefault(); 
     storeUrl = $(this).attr('href'); 
     if (localStorage.getItem(storeUrl)) { 
      //load local 
     } else { 
      $.ajax({ 
       url: storeUrl, 
       cache: true, 
       crossDomain: true 
      }).done(function(html) { 
       localNews = html; 
       console.log(localNews); 
       localStorage.setItem(storeUrl, localNews); 
      }); 
     } 
    }); 
+0

我可以看到你要去哪裏,但我的問題是更多如何加載實際你添加的if語句裏面的內容 – HjalmarCarlson

+0

你可以將它附加到body,或者加載到iframe – salexch

0

所以基本上要加載通過Ajax本地文件?可以完成,但只需對Ajax調用做一些小的調整即可。因此,改變這種:

$.ajax({ 
    url: storeUrl, 
    cache: true, 
    crossDomain: true 

要這樣:

$.ajax({ 
    url: storeUrl, 
    cache: true, 
    crossDomain: true, 
    async: false, 
    dataType: 'html', 
    contentType: 'text/html;charset=utf-8' 

注意asyncdatatypecontentType。自從我編碼以來已經有一段時間了,但我相信關鍵參數是async,但也需要datatypecontentType