简体   繁体   English

当我尝试检索对象时,sessionStorage不起作用

[英]sessionStorage doesn't work when I try to retrieve an object

I am using an AJAX call to a web method to validate a user, and when the web call returns, I am trying to use this code to populate sessionStorage with an object so I can then access the user's information from other pages: 我正在使用对Web方法的AJAX调用来验证用户,并且当Web调用返回时,我试图使用此代码来用对象填充sessionStorage ,以便随后可以从其他页面访问用户的信息:

 success: function (r) {
                    var info = JSON.parse(r.d);
                    if (info.Reply == 'OK')
                    {
                        $('#signinForm').html("<p>You're logged in!</p>");
                        var MemberObject = { 'MemberName': $('#MemberName').val() };
                        sessionStorage.setItem('MemberObject', JSON.stringify(MemberObject));
                    }
                },
                error: function (r) {
                    alert(r.responseText);
                },
                failure: function (r) {
                    alert(r.responseText);
                }

To test this, I added this block of code at the top of the page to replace the login dialogue with a welcome message for a logged-in user by retrieving the object I added to sessionStorage , but it doesn't work: 为了测试这一点,我在页面顶部添加了此代码块,以通过检索添加到sessionStorage的对象来用登录消息欢迎登录消息来替换登录对话框,但是它不起作用:

$(document).ready(function () {
        function isObject(val) {
            if (val === null) { return false; }
            return ((typeof val === 'function') || (typeof val === 'object'));
        }

        var mObj = sessionStorage.getItem('MemberObject');

        if (isObject(mObj))
        {
            var data = JSON.parse(mObj);
            $('signinForm').html("<p>Welcome, " + data.MemberName + "!</p>");
        }

Why doesn't sessionStorage working? sessionStorage为什么不起作用?

As @nnnnnn said in comment, the if (isObject(mObj)) condition will always return false. 正如@nnnnnn在评论中所说, if (isObject(mObj))条件将始终返回false。 mObj is a string at that point in time. mObj在那个时间点是一个字符串。 To resolve the problem, use JSON.parse() before the condition instead of after it, or use a different condition. 要解决此问题,请在条件前而不是条件后使用JSON.parse() ,或使用其他条件。

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

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