如何保存 javascript 变量

How to save a javascript variable

我有一个 javascript 变量,它由 .php 脚本中的 javascript 函数递增,唯一的问题是调用该函数时页面会重新加载,所以当页面重新加载或您输入时,我需要一些方法来保存变量相同。 我知道您可以进行本地保存,但我不确定它是否会在您离开网站时保存变量。

我的变量在 html 脚本中。

<script type="text/javascript"> 

                    var varNumber= 1;
                    document.getElementById("varNumber").innerHTML = varNumber;
                    document.getElementByID("varNumber").value = varNumber;


                    function addToVariable() {
                        varNumber= varNumber+ 1 ;
                        document.getElementById("varNumber").innerHTML = varNumber;
                    }

                </script>

您可以在客户端使用localStorage

<script>
  localStorage.setItem("mykey",99); // set a variable

  var varNumber = localStorage.getItem("mykey"); // retrieve variable
</script>

以下是在页面刷新时保存 JavaScript 变量的三种客户端方法,并说明了它们可以保留数据多长时间。

使用本地存储保存一个 JavaScript 变量

使用本地存储保存 JS 变量对于现代浏览器来说既简单又方便。

var get = function (key) {
  return window.localStorage ? window.localStorage[key] : null;
}

var put = function (key, value) {
  if (window.localStorage) {
    window.localStorage[key] = value;
  }
}

要保存和读取对象而不是简单变量:

localStorage.yourObject = JSON.stringify(obj);

obj = JSON.parse(localStorage.yourObject || "{}");

坚持:

User agents may, if so configured by the user, automatically delete stored data after a period of time.

For example, a user agent could be configured to treat third-party local storage areas as session-only storage, deleting the data once the user had closed all the browsing contexts that could access it.

This can restrict the ability of a site to track a user, as the site would then only be able to track the user across multiple sessions when he authenticates with the site itself (e.g. by making a purchase or logging in to a service).

However, this also reduces the usefulness of the API as a long-term storage mechanism. It can also put the user's data at risk, if the user does not fully understand the implications of data expiration.

参考文献:


使用 cookie 保存 JavaScript 变量

使用 cookie 保存变量:

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

坚持:

Session cookies - these are temporary and are erased when you close your browser at the end of your session.

Persistent cookies - these remain on the client hard drive until they are erased or expire.

This is ultimately user-dependent. They could be paranoid about cookies and local storage, and set them to session-only or none at all.

REF: Set cookie and get cookie with JavaScript


使用 window.name

保存 JavaScript 变量

您还可以使用 window 的名称 window.name 来存储使用 JavaScript session 的信息。

坚持:

This only works as long as the same window/tab is used.

REF: http://www.thomasfrank.se/sessionvars.html

您可以使用 AJAX 来执行 PHP,例如:

<?php
session_start(); $r = array();
if(isset($_POST['holdNumber'])){ // assumes {holdNumber:numberHere} sent through AJAX
  if(preg_match('/^\d+$/', $_POST['holdNumber']){
    $r['heldNumber'] = $_SESSION['holdNumber'] = $_POST['holdNumber'];
  }
  else{
    // holdNumber hack
  }
}
elseif(isset($_POST['load'])){
  if(+$_POST['load'] === 1){ // assumes sending {load:1} in AJAX
    if(isset($_SESSION['holdNumber']){
      $r['heldNumber'] = $_SESSION['holdNumber'];
    }
    else{
      $r['heldNumber'] = $_SESSION['holdNumber'] = 0;
    }
  }
  else{
    // load hack
  }
}
echo json_encode($r);
?>