2010-02-24 29 views
9

我在玩與http://www.w3.org/TR/offline-webapps/navigator.onLine

發現不完整的榜樣,但是,我心疼地看到它的評論一樣:

"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 
} 

但我不知道是什麼連我將配合這一點。

+6

我會建議不要在每次擊鍵時保存到數據庫。使用setTimeout在用戶暫停鍵入後觸發保存* n *秒。否則,網絡延遲會導致輸入一個噩夢。我自己,我會把保存到每個輸入的onblur處理程序中。 – Robusto 2010-03-01 18:38:06

+0

感謝Robusto的評論。 – 2010-03-01 22:54:09

回答

10

它看起來像你對我是沿着

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連接。如果互聯網連接可用,請重複彈出陣列頂部的元素並通過網絡發送,直到數組爲空。

1

如果navigator.online可以將本地數據庫與在線存儲庫同步,那麼您可能不需要'其他',因爲您已經在本地存儲了。它可能會更好,但添加eventlisteners(在窗口對象上)「離線」和「在線」事件,並觸發(並取消)使用這些事件進行同步。在線/離線狀態處理on this hacks.mozilla.org page

退房的例子來看一下this ajaxian article about the webkit stickynotes html5-implementation(不在線時同步雖然)

+0

hacks.mozilla頁面僅使用清單文件的詳細信息,而不是完整的SQL數據庫用於脫機存儲。 – 2010-03-08 00:07:15

+0

確實,它使用localstorage來存儲本地日期,而不是webdb(本地sql數據庫),因爲firefox不會,也許永遠不會(請參閱http://blog.futtta.be/2009/11/18/chrome-opera- to-support-html5-webdb -ff-ie-wont /)支持webdb。 – futtta 2010-03-08 03:20:35

相關問題