【问题标题】:navigator.onLinenavigator.onLine
【发布时间】:2010-03-08 08:05:18
【问题描述】:

我在玩 http://www.w3.org/TR/offline-webapps/ 上的不完整示例

但是看到里面的 cmets 我很心疼:

"renders the note somewhere", and
"report error", and
"// …"

那么,有人可以帮我写一个有效的例子吗?到目前为止,这是我所得到的:

<!DOCTYPE HTML>
<html manifest="cache-manifest">
<head>
<script>
var db = openDatabase("notes", "", "The Example Notes App!", 1048576);

function renderNote(row) {
  // renders the note somewhere
}
function reportError(source, message) {
  // report error
}

function renderNotes() {
  db.transaction(function(tx) {
    tx.executeSql('CREATE TABLE IF NOT EXISTS Notes(title TEXT, body TEXT)',
      []);
    tx.executeSql(‘SELECT * FROM Notes’, [], function(tx, rs) {
      for(var i = 0; i < rs.rows.length; i++) {
        renderNote(rs.rows[i]);
      }
    });
  });
}

function insertNote(title, text) {
  db.transaction(function(tx) {
    tx.executeSql('INSERT INTO Notes VALUES(?, ?)', [ title, text ],
      function(tx, rs) {
        // …
      },
      function(tx, error) {
        reportError('sql', error.message);
      });
  });
}


</script>
<style>
label {
    display:block;
}
</style>
</head>
<body>
<form>
<label for="mytitle">Title:</label>
<input name="mytitle">
<label for="mytext">Text:</label>
<textarea name="mytext"></textarea>
<!-- There is no submit button because I want to save the info on every keystroke -->
</form>
</body>
</html>

我也知道我必须将它合并到某个地方:

if (navigator.onLine) {
   // Send data using XMLHttpRequest
} else {
   // Queue data locally to send later
}

但我什至不确定我也会把它系起来。

【问题讨论】:

  • 我建议不要在每次击键时保存到数据库。在用户暂停输入后,使用 setTimeout 触发保存 n 秒。否则网络延迟将使打字成为一场噩梦。我自己,我会将保存到每个输入的 onblur 处理程序中。
  • 感谢 Robusto 的评论。

标签: javascript html


【解决方案1】:

在我看来你是在追求类似的东西

function save() {
    if (navigator.onLine) {
       // Send data using XMLHttpRequest
    } else {
       // Queue data locally to send later
    }
}

<textarea name="mytext" onkeyup="save();"></textarea>

但是,使用 Robusto 提到的超时(我认为这也是 GMail 做事的方式)。

如果是您担心的“在某处渲染注释”等,则该部分由您填写。您必须通过从数据库中选择数据来填写,然后将其填充到页面上的元素。

function renderNote(row) {
    $('notes').innerHtml = $('notes').innerHtml + row.body;
}

这是我能从目前的规范中得出的最好结果 - 但是请注意,规范目前不完整,您还无法在 w3 网站上找到它的最终版本。

如果您对如何在本地对数据进行排队感到好奇,那么即使是数组也应该这样做。将每个本地请求推送到阵列的末尾(并可能同时将其保存在本地)并定期检查活动的互联网连接。如果 Internet 连接可用,则重复从数组中弹出顶部元素并通过网络发送它,直到数组为空。

【讨论】:

    【解决方案2】:

    如果 navigator.online 您可以将本地数据库与在线存储库同步,您可能不需要“else”,因为您已经在本地存储。不过,最好为“离线”和“在线”事件添加事件监听器(在窗口对象上)并使用这些事件触发(和取消)同步。

    查看在线/离线状态处理示例on this hacks.mozilla.org page 并查看this ajaxian article about the webkit stickynotes html5-implementation(虽然在线时不同步)

    【讨论】:

    • 那个 hacks.mozilla 页面只详细说明了使用清单文件,而不是用于离线存储的完整 sql 数据库。
    • 确实,它使用 localstorage 来存储本地日期,而不是 webdb(本地 sql db),因为 firefox 不支持并且可能永远不会(参见 blog.futtta.be/2009/11/18/…)支持 webdb。
    猜你喜欢
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多