Reputation: 136
I am new to JS and just had a doubt on my foll. coding
getInput.js
setVal(5,6);
global.js
var x ; var y ;
function setVal(a,b){
x=a;
y=b;
}
function getVal(){
//code to return the value of x and y as an array
}
getVal.js
arr = getVal();
1.html :
<html>
<head>
<script src='global.js'></script>
<script src='getInput.js'></script>
</head>
<body>
<!-- content of body -->
<!--Code to navigate to 2.html -->
</body>
</html>
2.html :
<html>
<head>
<script src='global.js'></script>
<script src='getVal.js'></script>
</head>
<body>
<!-- content of body -->
</body>
</html>
When 2.html is redirected , it shows the array as "undefined"
I know that variable can be passed using cache between the pages and there are various other methods to do the same . But i would like to know a concrete reasong why the above method doesnt work. It would be appreciable if anyone lets me know on better solution on the same .
Upvotes: 0
Views: 63
Reputation: 583
There are two storage objects available for every browser. 1. Local Storage. 2. Session Storage. If your intent is to have the variable only for the session, make use of the sessionStorage object. As per your requirement, you can use it like this.
sessionStorage.setItem("x", 5);
sessionStorage.setItem("y", 6);
You can get the values of "x" and "y" in any page within the session by
var x = sessionStorage.getItem("x");
var y = sessionStorage.getItem("y");
Local storage also does the same job. But it just keeps the value even after the session has expired. For more information on session and local storage objects, refer the link below. Hope it helped.
https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API
Upvotes: 0
Reputation: 2245
Use cookies to set and get the values of your array in other html pages, like this:
To set the cookie:
document.cookie="x=John; y=Mike";
To get the cookie value:
var arr = document.cookie;
Then you can use a string tokenizer to tokenize arr.
-- or --
Use local storage, like this:
To set the item:
localStorage.setItem('arr',JSON.stringify(arr));
To get the item:
arr = localStorage.getItem('arr');
arr = JSON.parse(arr);
Upvotes: 0
Reputation: 2856
Because when you move to a new page in this case 2.html
, the previous page is destroyed and the new page is parsed and loaded. Therefore your script global.js
is re-executed on page 2.html
and when you called the function getVal()
, these variables were undefined
since they do not have any values assigned to them.
HTTP is stateless, it cannot retain information between different requests. You need some kind of mechanism to store those values either in cookies, or local storage or in some kind of database.
Upvotes: 1