简体   繁体   English

页面刷新时如何保留javascript数组?

[英]How to retain javascript array while page refresh?

PHP file PHP文件

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

Javascript file Javascript文件

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?我应该将数组放在 PHP 会话中还是隐藏字段中? If yes, then how?如果是,那么如何?

Use localStorage API for this purpose, Use setItem() method and do stringify the array before storing into the localStorage .为此使用localStorage API,使用setItem()方法并在存储到localStorage之前对数组进行字符串化。 You can retrieve the stored item by getItem() and parse the stored array using JSON.parse() , something like您可以通过getItem()检索存储的项目并使用JSON.parse()解析存储的数组,例如

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您可以使用浏览器的内部存储: 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") localStorage.setItem("storageName", myArray)然后检索它localStorage.getItem("storageName")var myArray = localStorage.getItem("storageName")

probably the easiest way would be using jQuery cookie可能最简单的方法是使用 jQuery cookie

edit var myArray = [] /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.如果您想使用 PHP 会话,我会利用 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 save_array.php

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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