2013-01-23 17 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