简体   繁体   English

如何将项目添加到可以在另一个页面上访问的javascript数组?

[英]How to add items to javascript array that can be accessed on another page?

I have a problem. 我有个问题。 I have created a php website and with every item there is a "request a quote" button. 我创建了一个php网站,每个项目都有一个“请求报价”按钮。 on clicking the button, i want the item name to be added to an array (which i am doing through Javascript).subsequently, the array is to be added to the request form "message" field on contact.php. 点击按钮,我想要将项目名称添加到一个数组(我正在通过Javascript进行)。随后,该数组将被添加到contact.php上的请求表单“message”字段中。 i have used this - 我用过这个 -

<script language="javascript">
// Empty array
var empty = [];

// Array containing initial elements.
var arrayitem= ['hello'];

alert(arrayitem[1]);
function myFunction(item) {
arrayitem.push(item);
var Items='';
for (var i = 0; i < arrayitem.length; i++) {
Items=Items+','+(arrayitem[i]);
   alert(Items);

};
document.getElementById("message").value=arrayitem[1];
}
</script>

on header.php page, which i include on every page. 在header.php页面上,我包含在每个页面上。 I have two more pages- 1. computers.php- that contains computers as items and 2. softwares.png- that contains softwares as items. 我有两个页面 - 1. computers.php-包含计算机作为项目和2. softwares.png-包含软件作为项目。

Now the problem is, when i add items from one page, they are appended to the array and it works fine, but when i navigate to another page, the items added from previous page get removed from the array ..and moreover i cant see the araay items in the "message field of contactus.php.".please help 现在的问题是,当我从一个页面添加项目时,它们被附加到数组并且它工作正常,但是当我导航到另一个页面时,从上一页添加的项目将从数组中删除..而且我无法看到“contactus.php的消息字段”中的araay项目。请帮助

JavaScript is a client side scripting language, it is not designed to persist variable values between page requests. JavaScript是一种客户端脚本语言,它不是为了在页面请求之间保持变量值而设计的。 If you want to access JavaScript variables on another page you will have to pass them along with the request for the new page, so that the new page can reinstate them. 如果要在另一个页面上访问JavaScript变量,则必须将它们与新页面的请求一起传递,以便新页面可以恢复它们。

Besides posting it to the next page along with the request, in newer browsers you can use localStorage: 除了将其与请求一起发布到下一页,在较新的浏览器中,您可以使用localStorage:

// Store the array
var array = [1, 2, 3];
localStorage['array'] = JSON.stringify(array);

// Retrieve the array
var storedArray = JSON.parse(localStorage['array']);

In older and newer browsers you can use cookies: 在较旧和较新的浏览器中,您可以使用Cookie:

// Store the array in a cookie
var array = [1, 2, 3];
var jsonArray = JSON.stringify(array);
setCookie('mycookie', jsonArray , 1);

function setCookie(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=/';
}

// Retrieve the array from a cookie
var jsonArrayFrom Cookie = JSON.parse(getCookie('mycookie'));

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

You could try using the browser's localStorage to store data in between page visits. 您可以尝试使用浏览器的localStorage在页面访问之间存储数据。

Try this JavaScript in your header.php: 在header.php中尝试使用此JavaScript:

localStorage.setItem("preference", "10");

And then in your contact page try this: 然后在您的联系页面中试试这个:

console.log(localStorage.getItem("preference"));

You should see "10" in your browser console. 您应该在浏览器控制台中看到“10”。

Here's more info about localStorage: http://diveintohtml5.info/storage.html 以下是有关localStorage的更多信息: http//diveintohtml5.info/storage.html

You should save the array and post it to the other page by using a form or other method. 您应该使用表单或其他方法保存数组并将其发布到其他页面。 Javascript is not persisted. Javascript没有持久化。

You can use Webstorage for in-between pages persistence. 您可以将Webstorage用于中间页面持久性。 Create a JSON object from your array like this: 从您的数组创建一个JSON对象,如下所示:

var myArrayString = JSON.stringify(myArray);

And store it in a key in the webstorage: 并将其存储在webstorage中的密钥中:

sessionStorage.setItem('arrayStore',myArrayString);

You can read this key back in another page: 您可以在另一页中阅读此密钥:

sessionStorage.getItem('arrayStore'); //returns 'myArrayString'

...or simply reference the sessionStorage object: ...或者只是引用sessionStorage对象:

sessionStorage.arrayStore; //returns 'myArrayString'

Try to use cookies on javascript and then retrieve it on PHP with $_COOKIE var. 尝试在javascript上使用cookie,然后使用$ _COOKIE var在PHP上检索它。

http://www.php.net/manual/en/features.cookies.php http://www.php.net/manual/en/features.cookies.php

Regards. 问候。

You could write the information into cookies via PHP and read them via JavaScript, in the example jQuery is assumed: 您可以通过PHP将信息写入cookie并通过JavaScript读取它们,在示例中假设jQuery:

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"/>
    <script src="http://cachedcommons.org/cache/jquery-cookie/0.0.0/javascripts/jquery-cookie.js"/>
</head>
<body>
<h1>Cookie</h1>
<?php
$expire = time() + 60 * 60 * 24 * 30;
setcookie('some_cookie', "fnord", $expire);
?>
<script type="text/javascript">
    console.log($);
    $(document).ready(function () {
        alert($.cookie("some_cookie"));
    });
</script>
</body>
</html>

If you only need to support modern browser, you better work with localStorage, there also libaries avaiable to prevent you from reinventing the wheel. 如果您只需要支持现代浏览器,那么最好使用localStorage,还有一些可以防止您重新发明轮子。

Thanks All for your solutions.. I have used sessionStorage to store the items. 谢谢所有的解决方案..我使用sessionStorage存储项目。 and retrieve them on the contact page. 并在联系页面上检索它们。 i am providing the code. 我提供的代码。 may be it can help someone- included this in header.php- 可能它可以帮助某人 - 包括在header.php-

<script language="javascript">

function myFunction(item) {
sessionStorage.setItem(item,item);
var keyval=sessionStorage.item;
for(var i = 0; i < sessionStorage.length; i++)  
{  
    var keyName = sessionStorage.key(i);  
    var itemvalue = sessionStorage.getItem(keyName); 
      alert(keyName + " = " + itemvalue);  


}  

}
</script>

and in contactus page- 并在联络页面 -

 for(var i = 0; i < sessionStorage.length; i++)  
{  
    var keyName = sessionStorage.key(i);  
    var itemvalue = (i+1)+"-"+sessionStorage.getItem(keyName); 
     document.contact.message.value=document.contact.message.value+"\n"+itemvalue ;
}  

Hope it helps!!!! 希望能帮助到你!!!! Thanks all!! 谢谢大家!!

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

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