0

I need help to transfer an array from one page to another page. Following is the code that I created with a list of names. In another papge, I want to this array and also print them out. I am wondering whether I could get this array by javascript. Thank you so much! I have seperated two paragrahs of code so that you can easily read them. Thanks a lot!

<html>
<head>
<title>ys</title>
</head>
<body>
<script type="text/javascript">
var aName = new Array;
aName[0] = "daniel";
aName[1] = "zhang";
aName[2] = "alex";
aName[3] = "yang";
aName[4] = "Amy";
aName[5] = "Wang";
aName[6] = "Vincent";
aName[7] = "Lee";

for (i=0; i<8; i++)
{
document.write(aName[i] + "<br>")
}
</script>
</body>
</html>

<html>
<head>
<title>get the array from s.html and print out</title>
</head>
<body>
<script type="text/javascript">


for (i=0; i<8; i++)
{
document.write(aName[i] + "<br>")
}
</script>
</body>
</html>

2 Answers2

1

You can use an external js file if your array is hard-coded.

somefile.js

var aName = ["daniel","zhang", "alex", "yang", "Amy", "Wang", "Vincent", "Lee"];

Html

<html>
   <head>
       <script type="text/javscript" src="somefile.js"></script>
   </head>
   <body>
       <script type="text/javascript">
          for (i = 0; i < aName.length; i++)
          {
             document.write(aName[i] + "<br>")
          }
       </script>
   </body>
</html>

Other ways: If you use modern browser you can user localStorage for storing big string and split it every time by divider. Or using cookies but it's ugly.

kush
  • 979
  • 1
  • 15
  • 32
Dvir
  • 3,287
  • 1
  • 21
  • 33
1

Ah, life-cycle management. Is it OK to send it as a parameter? For example,

https://www.google.com/search?q=weather

If yes, see https://stackoverflow.com/a/9146311/227646 which says

Encode the array as a request parameter.

You should turn your array into a URI encoded string, so probably passing through something like JSON first.

Then decode the parameter in the www.testpage.faces.html

How to get "GET" request parameters in JavaScript?

If no (sensitive information), we will have to store it in the browser somehow. Perhaps a cookie?

Community
  • 1
  • 1
kush
  • 979
  • 1
  • 15
  • 32