ต้องการเก็บข้อมูลส่วนที่ใช้บ่อยๆ ไว้ในฝั่ง user (browser) นั่นละ จะได้ลดการ query แต่ข้อมูลมันมีการเปลี่ยนแปลงด้วย ที่เก็บข้อมูลระยะยาวได้ในฝั่ง browser กลับออกแบบให้ localStorage เก็บข้อมูลถาวรโดยไม่มีการ expires เหมือน cookie ทำให้ต้องเขียน code จัดการเพิ่ม
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | <!doctype html> <html> <head> <meta charset="utf-8"> <title>Ajax: localStorage</title> </head> <body> <h1>localStorage</h1> <div class="col-sm-12" id="datasA"></div> <div class="col-sm-12" id="resultA"></div> <script src="../vendor/components/jquery/jquery.min.js"></script> <script> $(function() { function getDatas() { let cacheKey = 'memories'; if (cacheKey in localStorage) { let datas = JSON.parse(localStorage.getItem(cacheKey)); // if expired if (datas['expires'] < Date.now()) { localStorage.removeItem(cacheKey); getDatas() } else { setDatas(datas); } } else { $.ajax({ "dataType": "json", "success": function(datas, textStatus, jqXHR) { let today = new Date(); datas['expires'] = today.setDate(today.getDate() + 7) // expires in next 7 days setDatas(datas); localStorage.setItem(cacheKey, JSON.stringify(datas)); }, }); } } function setDatas(datas) { // display json as text $('#datasA').text(JSON.stringify(datas)); // your code here let html = ''; $.each(datas.datas, function(index, value) { html += '<br>' + index + ' = ' + value; }); $('#resultA').html(html); } // call getDatas(); }); </script> </body> </html> |
ข้อมูลที่ call ผ่าน ajax จะโดนเก็บใน localStorage แต่เวลาใช้ก็จะเอามาเทียบ expires ก่อน ถ้ายังไม่หมดอายุก็เอามาใช้ ถ้าหมดอายุไปแล้วก็ call ใหม่ ลองดัดแปลงดูให้เหมาะกับงานดูครับ