JSON解析返回未定义的值

时间:2018-12-26 06:52:55

标签: javascript php json local-storage

我正在研究阅读历史记录系统。当用户访问某个帖子时,该帖子将使用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 /"
    }
]

但是,结果不断获得不确定的值,是什么引起问题?以及如何解决?

1 个答案:

答案 0 :(得分:0)

设置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 [];
}