简体   繁体   中英

JavaScript modifying a variable in one file and reading it in another

Is there any way to modify a global var within a function and then using it in another page? Let me explain better my situation: I have two HTML files, "Index.html" and "character.html". In Index, I have related this JS code:

var pcharacter = "initialValue";

document.getElementById("barbarianClass").onclick = function(event){
    event.preventDefault();
    pcharacter = "barbarian"; // the important line here...
    location.href = "pages/character.html";
}

The element "barbarianClass" is a link, that's why I blocked the default behavior with preventDefault() until I have given a value to my pcharacter var. Now, I have character.html, that has the following one single JS line code attached:

alert(pcharacter);

In character.html, I have both JS files related, how it should be done:

<script type="text/javascript" src="indexCode.js"></script>
<script type="text/javascript" src="charsCode.js"></script>

The problem is that when I click the link "barbarianClass" and my character.html page shows, the var pcharacter showed in the alert is "initialValue", even when I said it to have the value "barbarian" inside the event attached to the link before opening the page. Of course, I have plans for that variable, but for the question, the alert is easier. Could someone, please, tell me why the initialValue is kept? Is there any obscure rule in JS that says that when you load a JS document, global vars can't be changed anymore or something like that? I doesn't make any sense...

You can save data in cookie

function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+d.toUTCString();
  document.cookie = cname + "=" + cvalue + "; " + expires;
}

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

http://www.w3schools.com/js/js_cookies.asp

your code will be

/*save data*/
document.getElementById("barbarianClass").onclick = function(event){
  event.preventDefault();
  setCookie('pcharacter', 'barbarian', 1)
  location.href = "pages/character.html";
}

/*get data*/
alert(getCookie('pcharacter'));

What you are trying to do is simply not possible with variables alone , as for the reason highlighted by someone in your comments

Lets assume this is possible - would you want the page that has your bank details being accessed via javascript variables on a different page?

You should use cookies (client-side) or sessions(server-side) to accomplish this task. This is how you set a cookie in javascript:

document.cookie = "pcharacter=barbarian"

and then you can access this cookie in all other pages by this simple function :

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

console.log(getCookie("pcharacter"));

You can also set an expiry time for your cookies .

Ummmmmmm...well....banking problems aside :-)

To answer your question - the answer is both yes and no. If what you are going to do is to directly load in a new web page then no - your global variables will disappear like cotton candy at a carny show.

BUT! If instead, you use jQuery's getScript() function, then you can load in a new web page and keep your global variables. All you have to do is to convert your incoming web page into hexadecimal so all of the different letters like the less than sign, single, and double quotes don't muck things up, unconvert it once you have it, and then replace your web page or insert your web page/part as you wish.

To convert it to hex all you need is the bin2hex() function in PHP. To unhex something in Javascript you can go and get my toHex() and fromHex() functions on GitHub.

Also, you might want to think about sending everything back to the server in hex as well so script kiddies have a bit harder time giving themselves a +1000 weapon. Just a thought. It won't slow them down a lot - but every little bit helps. :-)

You can use localStorage to pass data from one file to another. The basic syntax is:

if (typeof(Storage) !== "undefined") {
    // Code for localStorage/sessionStorage.
} else {
    // Sorry! No Web Storage support..
}

Setting a value:

localStorage.setItem('myObj', 'My Object');

And getting a value:

localStorage.getItem('myObj');

If localStorage is not supported, you can always fall back to one of the cookies or URL rewriting. otherwise you can use window.name also

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