close
今天和同學討論如何在網頁間傳值的問題,在HTML 5中有Webstorage 這個功能,分別有localStorage和sessionStorage二種方式。

差別在二者資料保存時間上的差別。

鈼別寫二個程式webstorage.html和showstorage.html放在同一個目錄下,

webstorage.html 如下

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Webstorage Store</title>
</head>
<body>

<div id="result"></div>

<script>
// 判斷可不可以用
if (typeof(Storage) !== "undefined") {
    // 儲存資料
    localStorage.setItem("lastname", "Smith");
    // 取得資料並顯示
    document.getElementById("result").innerHTML = localStorage.getItem("lastname");
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>

</body>
</html>

 

另一個程式showstorage.html如下:

 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Webstorage getData</title>
</head>
<body>

<div id="result"></div>

<script>

    alert(localStorage.getItem("lastname"));
    
   console.log("helllo");

</script>

</body>
</html>
</html>

 

結果:

Screen Shot 2022-05-17 at 9.22.44 PM.png

可在先執行webstorage.html之衟執行showstorage.html顯示內容。代表資料己經正確傳輸。

至於sessionStorage同學可以自行試試看。應該網頁如果關畢儲存資料就會消失的差別。

這個看來是目前較簡單方法,但需要支持HTML的流覧器才行。

 

 

arrow
arrow
    全站熱搜

    liusming 發表在 痞客邦 留言(0) 人氣()