简体   繁体   中英

How to retain javascript array while page refresh?

PHP file

<input type="text" id="txtMyText">
<button type="button" id="myButton" onclick="addItemToArray()">Add to Array</button>

Javascript file

var myArray = []

function addItemToArray()
{
    myArray.push(document.getElementById("txtMyText").value);
}

Whenever I enter some value in a text field and hit the button, value gets stored in the array. When a page is refreshed, my array becomes empty. I want to retain its elements until I remove them manually. How do I retain them? Should I put array in PHP session or hidden field? If yes, then how?

Use localStorage API for this purpose, Use setItem() method and do stringify the array before storing into the localStorage . You can retrieve the stored item by getItem() and parse the stored array using JSON.parse() , something like

if(localStorage.getItem('textValues') == null){
    var myArray =[];
}else{
    myArray =  JSON.parse(localStorage.getItem('textValues'));
   //-----------^parse the item by getting---^--stored item
}

function addItemToArray(){
    myArray.push(document.getElementById("txtMyText").value);
    localStorage.setItem('textValues', JSON.stringify(myArray));
    //------------^store the item by stringify--^
}

DEMO

You could use the browser's internal storage: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage

Store the array:

sessionStorage.setItem("items", JSON.stringify(items));

Get the array from storage:

var items = JSON.parse(sessionStorage.getItem("items"));

To retain it on refresh you are going to need to store in local storage. localStorage.setItem("storageName", myArray) then to retrieve it localStorage.getItem("storageName") or var myArray = localStorage.getItem("storageName")

probably the easiest way would be using jQuery cookie

edit var myArray = [] /edit

if ($.cookie('arrayItems')){
      myArray=JSON.parse($.cookie('arrayItems'));
}


 function addItemToArray()  
 {
   myArray.push(document.getElementById("txtMyText").value);
  $.cookie('arrayItems',JSON.stringify(myArray));
 }

If you want to use a PHP session, I would take advantage of AJAX. You'll need to create a file to handle the array as you create it. Here's a simple example.

Your first page

<?php 
    //start the PHP session to save your array in
    session_start(); 
?>

<script type="text/javascript">
var myArray = [];
<?php
    if(isset($_SESSION['myArray'])) {
        foreach($_SESSION['myArray'] as $item){
            // prepopulate the session array from PHP
            echo "myArray[] = ".$item.";";
        }
    }
?>
function addItemToArray(){
    var addvalue = document.getElementById("txtMyText").value;
    myArray.push(addvalue);
    if (window.XMLHttpRequest){  var xmlhttp=new XMLHttpRequest();  }else {  var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  }
    xmlhttp.onreadystatechange=function()  {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)    {
            document.getElementById("myDiv").innerHTML += xmlhttp.responseText .", ";
        }
    }
    xmlhttp.open("GET","save_array.php?newValue="+,true);
    xmlhttp.send();
}
</script>

<div id="show_my_array">
    <?php
        //show array saved from last time
        if(isset($_SESSION['myArray'])) {
            foreach($_SESSION['myArray'] as $item){
                // prepopulate the session array from PHP
                echo $item.", ";
            }
        }
    ?>
</div>
<input type="text" id="txtMyText">
<button type="button" id="myButton" onclick="addItemToArray()">Add to Array</button>

save_array.php

<?php
session_start();
if(!isset($_SESSION['myArray'])){
    $_SESSION['myArray'] = array();
}
$_SESSION['myarray'][] = $_GET['newValue'];
echo $_GET['newValue'];
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM