简体   繁体   中英

session storage value is null while I have given a value to this session storage in another JS file

I have two JS files and in the first one I am initializing a session storage using ajax, so I want use this session storage value in my another JS files. but the problem is that the session storage in another files doesn't get any value while I have set it in the first initializing JS file earlier. my sample code is given as bellow:

JS file 1 (initializing JS file that has to be run at first):

   $.post(  
        "mypage.php",
        {    

        },function(data) {
   sessionStorage.setItem("data_kind", data.kind);
        }, 'json'
    ); 

js file 2 and others (is going to use data_kind which have been initialized in JS file 1):

var my_data_kind = sessionStorage.getItem("data_kind");
console.log(my_data_kind); // it returns null and dont get any value!!!

You'll only be able to read the value from storage after the AJAX request completes.

$.post() returns a deferred / promise-like object. Use that to chain something to run after the request completes.

For example, assuming your two JS files are included in this order

<script src="the-one-that-does-the-ajax-request.js"></script>
<script src="the-one-that-reads-from-session-storage.js"></script>
// the-one-that-does-the-ajax-request.js

const myPagePromise = $.post("mypage.php", {}, data => {
  sessionStorage.setItem("data_kind", data.kind);
}, "json")
// the-one-that-reads-from-session-storage.js

myPagePromise.then(() => {
  var my_data_kind = sessionStorage.getItem("data_kind")
  console.log(my_data_kind)
})

You have to make sure your sessionStorage.setItem("data_kind", data.kind) is already executed at first and make sure you have the right or import js file order

For me, when I debug my code I usually write console.log('execute blabla', data) to give myself confidence that my code in that line is running and loaded in the right order. Also, don't forget to delete the console.log when the feature is finished

And, closing a tab/window clear objects in sessionStorage as documented here https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

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