[FE102] Part 2


Posted by yymarlerr on 2021-06-01

網頁的資料都存在哪裡

Cookie:

  • 小型文字檔,會自動帶到 server
    • 可以用 JavaScript 寫資料到 cookie
    • 或者 server response 資料到 cookie 中,response 會有一個叫 set cookie 的 header,瀏覽器看到這個 cookie 就會把資訊寫進去
  • 去 dev tool 的 storage 可以看到 cookies 存了很多 domain
  • 可以透過 cookie 去驗證身份

Local Storage:

  • 用戶端想要在瀏覽器存一些和伺服器無關的資訊時,會存在此
  • window.localStorage.setItem("key", value) 新增資料
    • 像是瀏覽器提供的 API
    • window 可加可不加
    • 儲存的內容有點像物件,value 只能是字串
  • window.localStorage.getItem("key") 可以取得資料
  • 範例:
<body>
  <div class="app">
    <div>
      <input class="text"><button>送出</button>
  </div>
  <script>
    const previousValue = window.localStorage.getItem("text")
    document.querySelector(".text").value = previousValue

    document.querySelector("button").addEventListener("click",
    function() {
      const value = document.querySelector(".text").value
      window.localStorage.setItem("text", value)
    }
    )
  </script>
</body>

Session Storage

  • 用法和 localStorage 一樣,唯資料只會存在同個頁面
  • 用在短時間內的資訊儲存









Related Posts

基礎電腦科學:演算法概要

基礎電腦科學:演算法概要

Day 62 - Coffee & Wifi Project

Day 62 - Coffee & Wifi Project

[CSS] box model/ display/ position

[CSS] box model/ display/ position


Comments