【问题标题】:JSON parse returning undefined valueJSON解析返回未定义的值
【发布时间】:2019-05-24 12:05:54
【问题描述】:

我正在开发阅读历史系统。当用户访问某个帖子时,该帖子将使用 json 保存在 localstorage 中,并显示在特定元素上,以便他们跟踪上次阅读。

ViewHistory = function() {
    this.config = {
        storageKey: 'viewHistory',
        primaryKey: 'id'
    };
    this.cache = {
        localStorage:  null,
        userData:  null,
        attr:  null
    };
};

ViewHistory.prototype = {
    init: function(config) {
        this.config = config || this.config;
        var _self = this;
        // Define localStorage
        if (!window.localStorage && (this.cache.userData = document.body) && this.cache.userData.addBehavior && this.cache.userData.addBehavior('#default#userdata')) {
            this.cache.userData.load((this.cache.attr = 'localStorage'));
            this.cache.localStorage = {
                'getItem': function(key) {
                    return _self.cache.userData.getAttribute(key);
                },
                'setItem': function(key, value) {
                    _self.cache.userData.setAttribute(key, value);
                    _self.cache.userData.save(_self.cache.attr);
                }
            };
        } else {
            this.cache.localStorage = window.localStorage;
        }
    },

    addHistory: function(item) {
        var items = this.getHistories();
        for(var i=0, len=items.length; i<len; i++) {
            if(item[this.config.primaryKey] && items[i][this.config.primaryKey] && item[this.config.primaryKey] === items[i][this.config.primaryKey]) {
                items.splice(i, 1);
                break;
            }
        }
        items.push(item);
        var json = JSON.stringify(items);
        this.cache.localStorage.setItem(this.config.storageKey, json);
    },

    getHistories: function() {
        var history = this.cache.localStorage.getItem(this.config.storageKey);
        if(history) {
            return JSON.parse(history);
        }
        return [];
    }
};

if(typeof localStorage !== 'undefined' && typeof JSON !== 'undefined') {
    var viewHistory = new ViewHistory();
    viewHistory.init({
        storageKey: 'viewHistory',
        primaryKey: 'id'
    });
}

//Output

var wrap = document.getElementById('viewed_history');

if(viewHistory && wrap) {
    var histories = viewHistory.getHistories();
    var list = document.createElement('ul')
    if(histories && histories.length > 0) {
        for(var i=histories.length-1; i>=0; i--) {
            var history = histories[i];
            var item = document.createElement('li');
            var link = document.createElement('a');
            link.href = history.url;
            link.innerHTML = history.title;
            item.appendChild(link);
            list.appendChild(item);
        }
        wrap.appendChild(list);
    }
}

我如何获取数据并将其存储到本地存储:

<?php global $post;
$kategori = get_the_category( $post->ID );?>
<script type='text/javascript'>
if(viewHistory) {
    var book = {
        "id": <?php echo $kategori[0]->term_id;?>,
        "title": '<?php echo $kategori[0]->name; ?>',
        "url": '<?php echo get_the_permalink(); ?>',
    viewHistory.addHistory(book);
}
</script>

Json.stringify 作为示例可以正常工作:

[
    {
        "id": 2,
        "title": "Book A Chapter 96",
        "url": "https:// Post URL /"
    },
    {
        "id": 39,
        "title": "Book B Chapter 153",
        "url": "https:// Post URL /"
    }
]

但是,结果不断得到未定义的值,是什么造成了问题?以及如何解决?

【问题讨论】:

  • Json.stringify() 真的会产生这样的输出吗?那不是 JSON :-?
  • 我不知道怎么显示,所以我从chrome开发者工具(应用程序)举个例子
  • 我修好了,这应该是正确的。
  • 在条件块中使用单个等于=(赋值)运算符是个坏主意......
  • 你的意思是在for循环中?我稍后会更改它...

标签: javascript php json local-storage


【解决方案1】:

设置 JSON 对象时请注意。键必须在引号中,值取决于它是布尔值、整数还是字符串(使引号括起来)。

我认为,在您的 JSON 中,您没有维护 json 格式。请参阅您的 son.stringify() 示例。

 var config = '{"storageKey": true,"primaryKey": "id"}';

并访问简单示例:

var a =JSON.parse(config)
        console.log(a.storageKey);

或者只是返回历史记录。

 getHistories: function() {
    var history = this.cache.localStorage.getItem(this.config.storageKey);
    if(history) {
        return history;
    }
    return [];
}

【讨论】:

  • storageKey 值是存储到localstorage的json名称
  • 但是在你的 this.config 对象中你是如何定义 this 的。
  • var config 不是 json,它用于命名 localstorage 并确定 id 是否相同。我从其他 var one 得到 json,我会更新问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 2020-12-27
  • 2017-03-26
  • 2021-01-08
  • 1970-01-01
  • 2014-08-14
相关资源
最近更新 更多