简体   繁体   中英

Global variables in JavaScript with multiple files

I have a file called index.php. With script tags, it references index.js.

I also have a file called payment.php. With script tags, it references payment.js.

I need to set a variable called seatSelected in index.js and then use it in payment.js. However, I do not want to reference index.js in payment.php.

I have tried to make a file called globals.js, reference it in index.php before index.js containing the following:

var selectedSeat;

function setSelectedSeat(seat){
    selectedSeat = seat;
}

function getSelectedSeat(){
    return selectedSeat;
}

And setting the value in index.js with:

setSelectedSeat("test");

Receiving it in payment.js with (referencing globals.ks in payment.php above payment.js):

alert(getSelectedSeat());

But it alerts 'undefined'. Am I doing something wrong? How can I reference this variable without referencing the file it is changed in?

You cannot access variables created from another page.

You could use localStorage with cookies as fallback.

function setSelectedSeat(seat){
    if(localStorage) {
      localStorage['selectedSeat'] = JSON.stringify(seat);
    }
    else {
      //add code to store seat in cookie
    }
}

function getSelectedSeat(){
    if(localStorage) {
      return JSON.parse(localStorage['selectedSeat']);
    }
    else {
      //add code to retrive seat in cookie
    }
}

You are trying to persist the state of variables while transitioning from one page to another and your application seems to have data that would require session expiry, I suggest you use sessionstorage . With help of polyfills you can give sessionstorage support till IE6 browser.

Benefit of using SessionStorage over LocalStorage

  • Session Storage persists the data only for a particular tab/window and the data is lost when the tab/window is closed.
  • As the data gets expired automatically you don't need to worry about session expiring.
  • You can expire your session at your will as well.
  • The data persists on page refreshes.

But Remember with sessionstorage you can only store strings key-value pattern. And you need to use JSON.stringify and JSON.parse method to store your complex objects in browser memory.

Here you can find a list of polyfills that you can use to provide the support of sessionstorage in non supporting browsers : https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#web-storage-localstorage-and-sessionstorage

Also you can read the following article to understand sessionstorage and localstorage in a better way: http://diveintohtml5.info/storage.html

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