admin管理员组

文章数量:1331632

I have a javascript variable, which is incremented by a javascript function in a .php script, only problem is that the page reloads when the function is called, so I need some way of saving the variable to be the same when the page is either reloaded or whenever you enter it. I know you can do a local save but I am not quiet sure if it saves the variable when you leave the website.

My variable is in a html script.

<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>

I have a javascript variable, which is incremented by a javascript function in a .php script, only problem is that the page reloads when the function is called, so I need some way of saving the variable to be the same when the page is either reloaded or whenever you enter it. I know you can do a local save but I am not quiet sure if it saves the variable when you leave the website.

My variable is in a html script.

<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>
Share Improve this question asked Mar 30, 2015 at 23:11 DevLivDevLiv 5737 silver badges19 bronze badges 5
  • is it global for the server or global per person? – user557846 Commented Mar 30, 2015 at 23:13
  • Have you looked into cookies? – Drakes Commented Mar 30, 2015 at 23:14
  • then you can use cache :) – Rajib Ghosh Commented Mar 30, 2015 at 23:16
  • You should use $_SESSION with PHP. JavaScript will load all the code again every time the page loads. JavaScript supports localStorage and sessionStorage in newer Browsers. Depending on how the page is reloading you could also use location.hash or location.search to get a value from a URL, as well. – StackSlave Commented Mar 30, 2015 at 23:21
  • $_SESSION is not suitable because in every request create it's own session... – Rajib Ghosh Commented Mar 30, 2015 at 23:26
Add a ment  | 

3 Answers 3

Reset to default 4

Here are three client-side methods to save JavaScript variables across page refreshes and descriptions on how long they can persist data.

Saving a JavaScript variable with local storage

Saving a JS variable using local storage is easy and convenient with modern browsers.

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

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

To save and read an object instead of a simple variable:

localStorage.yourObject = JSON.stringify(obj);

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

Persistence:

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.

References:

  • http://dev.w3/html5/webstorage/
  • Persisting values in JavaScript object across browser refresh
  • How persistent is localStorage?

Saving a JavaScript variable with cookies

Saving a variable with cookies:

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;
}

Persistence:

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


Saving a JavaScript variable with window.name

You could also use the window’s name window.name to store the information using a JavaScript session.

Persistence:

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

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

You can use localStorage on client side

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

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

You could use AJAX to execute PHP, like:

<?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);
?>

本文标签: phpHow to save a javascript variableStack Overflow