Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

persistence - Saving a Javascript variable for later usage?

I was wondering if there were a way to save one or more javascript variables to the local machine and then call on them later?

var a = b

and then when you go back to the webpage it remembers the value that B was?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you mean in a web browser, there are two options:

  • Cookies

  • Web storage (in your case, specifically, "local storage" as opposed to "session storage")

Cookies are universally supported by browsers, although users can turn them off. The API to them in JavaScript is really, really bad. The cookies also get sent to your server, so they increase the size of requests to your server, but can be used both client- and server-side.

Setting a cookie is easy, but reading a cookie client-side is a pain. Look at the MDN page above for examples.

Web storage is supported by all major modern browsers (including IE8 and up). The API is much better than cookies. Web storage is purely client-side, the data is not sent to the server automatically (you can, of course, send it yourself).

Here's an example using web storage: Live Copy

<label>Value: <input type="text" id="theValue"></label>
<input type="button" id="setValue" value="Set">
<script>
(function() {
  // Use an input to show the current value and let
  // the user set a new one
  var input = document.getElementById("theValue");

  // Reading the value, which was store as "theValue"
  if (localStorage && 'theValue' in localStorage) {
    input.value = localStorage.theValue;
  }

  document.getElementById("setValue").onclick = function () {
    // Writing the value
    localStorage && (localStorage.theValue = input.value);
  };
})();
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...