简体   繁体   English

会话存储值为空,而我在另一个 JS 文件中为此会话存储赋予了值

[英]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.我有两个 JS 文件,第一个我使用 ajax 初始化会话存储,所以我想在我的另一个 JS 文件中使用这个会话存储值。 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.但问题是,当我之前在第一个初始化 JS 文件中设置它时,另一个文件中的会话存储没有得到任何值。 my sample code is given as bellow:我的示例代码如下:

JS file 1 (initializing JS file that has to be run at first): JS文件1(初始化必须首先运行的JS文件):

   $.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): js 文件 2 和其他(将使用已在 JS 文件 1 中初始化的 data_kind):

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.您只能在 AJAX 请求完成后从存储中读取该值。

$.post() returns a deferred / promise-like object. $.post()返回一个延迟/类似承诺的对象。 Use that to chain something to run after the request completes.使用它来链接一些在请求完成后运行的东西。

For example, assuming your two JS files are included in this order例如,假设您的两个 JS 文件包含在此顺序中

<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你必须首先确保你的sessionStorage.setItem("data_kind", data.kind)已经被执行,并确保你有正确的或导入的 js 文件顺序

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.对我来说,当我调试我的代码时,我通常会写 console.log('execute blabla', data) 来让自己确信我在该行中的代码正在以正确的顺序运行和加载。 Also, don't forget to delete the console.log when the feature is finished另外,不要忘记在功能完成后删除console.log

And, closing a tab/window clear objects in sessionStorage as documented here https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage并且,关闭 sessionStorage 中的选项卡/窗口清除对象,如此处所述https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM