【问题标题】:Load page with HTML from web storage从网络存储加载带有 HTML 的页面
【发布时间】:2013-01-07 05:18:29
【问题描述】:

我正在测试一个使用本地存储的应用程序的概念,并且需要知道在存储内容后加载内容的最佳方式。

本质上,应用程序会预取内容,将其存储在本地,然后根据请求将其服务到新页面中。我需要用户能够单击链接 (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');
});
});

【问题讨论】:

  • 我认为这个链接可能会阻止你重新发明现有的东西:html5rocks.com/en/tutorials/appcache/beginner
  • 你忘记了 $('a').click(function(event) { 中的事件
  • @dystroy 如果我错了,请纠正我,但如果我们使用 PHP 模板引擎,这将不起作用。

标签: javascript jquery ajax html local-storage


【解决方案1】:
    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);
            });
        }
    });

【讨论】:

  • 我可以看到你的意图,但我的问题更多的是如何在你添加的 if 语句中加载实际内容。
  • 您可以将其附加到正文中,或加载到 iframe 中
【解决方案2】:

所以基本上你想通过 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    相关资源
    最近更新 更多