บบที่ 9 HTML5 Web Storage
Web Storage คือการเก็บข้อมูลแบบง่ายๆ ในรูป Key-Value โดยแยกย่อยได้อีก 2 อย่าง คือ
1.Local Storage จะเก็บข้อมูลไว้ได้นานและมากกว่า cookie หลายเท่า และข้อมูลจะยังคงอยู่แม้ว่าจะปิด browser หรือลบ cookie ไปแล้ว
2.session Storage เหมือนกัน Local Storage แทบทุกประการ ยกเว้นมันจะถูกลบค่าทิ้งทุกครั้งที่เราปิด browser
ในการใช้งาน Web Storage นั้น รองรับเฉพาะการเก็บข้อมูลที่เป็น String ดังนั้น หากเราต้องการเก็บ Object ทั้งก้อนลงใน Local Storage หรือ Session Storage ก็ต้องทำการแปลงข้อมูลจาก Object ให้เป็น String เสียก่อน บราวเซอร์ที่สนับสนุน HTML5 Web Storage คือInternet Explorer 8+, Firefox, Opera, และ, and Safari.
ตัวอย่าง
1.Local Storage
<html>
<body>
<div id="result"></div>
<script>
if(typeof(Storage)!=="undefined")
{
localStorage.lastname="Smith";
document.getElementById("result").innerHTML="Last name: " + localStorage.lastname;
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support web storage...";
}
</script>
</body>
</html>
ผลลัพธ์คือ
2.session Storage
<html>
<head>
<script>
function clickCounter()
{
if(typeof(Storage)!=="undefined")
{
if (sessionStorage.clickcount)
{
sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
}
else
{
sessionStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support web storage...";
}
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Click me!</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter is reset.</p>
</body>
</html>
ผลลัพธ์คือ
ข้อมูลอ้างอิง
http://www.w3schools.com