您的位置:首页 > Web前端 > JavaScript

【Web前端】:JavaScript操作Cookie实现“历史搜索”

2016-01-27 20:25 681 查看

导读

  其实实现历史搜索这一功能的思路很简单,这里就是总结一下js如何操作cookie。

一睹为快

        



                  【搜索页】

        



                 【搜索结果页】

需求

  将用户搜索过的关键字保存起来

实现思路

  用户通过点击热门搜索、历史搜索中的关键字或者是在搜索框输入关键字之后点击搜索按钮都会进入到搜索结果页面。所以,我们的思路是:

  当搜索结果页面加载完毕时,将关键字和关键字对应的链接地址存起来,当搜索页重新加载时,将保存的记录显示到界面上。

代码

公共js

[code]/**
 * History
 * 用法
 * var his = new History('key');  // 参数标示cookie的键值
 * his.add("标题", "连接 比如 http://www.baidu.com", "其他内容"); 
 * 得到历史数据 返回的是json数据
 * var data = his.getList();  // [{title:"标题", "link": "http://www.baidu.com"}]
 * 
 */
function History(key) {
    this.limit = 10;  // 最多10条记录
    this.key = key || 'y_his';  // 键值
    this.jsonData = null;  // 数据缓存
    this.cacheTime = 24;  // 24 小时
    this.path = '/';  // cookie path
}
History.prototype = {
    constructor : History
    ,setCookie: function(name, value, expiresHours, options) {
        options = options || {};
        var cookieString = name + '=' + encodeURIComponent(value);
        //判断是否设置过期时间
        if(undefined != expiresHours){
            var date = new Date();
            date.setTime(date.getTime() + expiresHours * 3600 * 1000);
            cookieString = cookieString + '; expires=' + date.toUTCString();
        }

        var other = [
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join('');

        document.cookie = cookieString + other; 
    }
    ,getCookie: function(name) {
        // cookie 的格式是个个用分号空格分隔
        var arrCookie = document.cookie ? document.cookie.split('; ') : [],
            val = '',
            tmpArr = '';

        for(var i=0; i<arrCookie.length; i++) {
            tmpArr = arrCookie[i].split('=');
            tmpArr[0] = tmpArr[0].replace(' ', '');  // 去掉空格
            if(tmpArr[0] == name) {
                val = decodeURIComponent(tmpArr[1]);
                break;
            }
        }
        return val.toString();
    }
    ,deleteCookie: function(name) {
        this.setCookie(name, '', -1, {"path" : this.path});
        //console.log(document.cookie);
    }
    ,initRow : function(title, link, other) {
        return '{"title":"'+title+'", "link":"'+link+'", "other":"'+other+'"}';
    }
    ,parse2Json : function(jsonStr) {
        var json = [];
        try {
            json = JSON.parse(jsonStr);
        } catch(e) {
            //alert('parse error');return;
            json = eval(jsonStr);
        }

        return json;
    }

    // 添加记录
    ,add : function(title, link, other) {
        var jsonStr = this.getCookie(this.key);
        //alert(jsonStr); return;

        if("" != jsonStr) {
            this.jsonData = this.parse2Json(jsonStr);

            // 排重
            for(var x=0; x<this.jsonData.length; x++) {
                if(link == this.jsonData[x]['link']) {
                    return false;
                }
            }
            // 重新赋值 组装 json 字符串
            jsonStr = '[' + this.initRow(title, link, other) + ',';
            for(var i=0; i<this.limit-1; i++) {
                if(undefined != this.jsonData[i]) {
                    jsonStr += this.initRow(this.jsonData[i]['title'], this.jsonData[i]['link'], this.jsonData[i]['other']) + ',';
                } else {
                    break;
                }
            }
            jsonStr = jsonStr.substring(0, jsonStr.lastIndexOf(','));
            jsonStr += ']';

        } else {
            jsonStr = '['+ this.initRow(title, link, other) +']';
        }

        //alert(jsonStr);
        this.jsonData = this.parse2Json(jsonStr);
        this.setCookie(this.key, jsonStr, this.cacheTime, {"path" : this.path});
    }
    // 得到记录
    ,getList : function() {
        // 有缓存直接返回
        if(null != this.jsonData) {
            return this.jsonData;  // Array
        } 
        // 没有缓存从 cookie 取
        var jsonStr = this.getCookie(this.key);
        if("" != jsonStr) {
            this.jsonData = this.parse2Json(jsonStr);
        }

        return this.jsonData;
    }
    // 清空历史
    ,clearHistory : function() {
        this.deleteCookie(this.key);
        this.jsonData = null;
    }
};


调用添加历史记录的方法

[code]document.onreadystatechange = function(){  
    if(document.readyState=="complete")  
    {  
        var his = new History('key');
        var keyword=document.getElementById("keyword").value;       
        his.add(keyword, "wx_searchPro.action?keyword="+keyword, "");

    }
}


显示历史记录到页面上

[code]$(document).ready(function(){
     var his = new History('key');
     var data = his.getList();
     for(var i=0;i<data.length;i++){

         var a=document.createElement('a');   
         var href=data[i].link;
         a.setAttribute('href',href);
         a.style["textDecoration"]="none";
         a.style["color"]="#000";       
         var t=document.createTextNode(data[i].title);
         a.appendChild(t);
         var span=document.createElement("span");
         var space=document.createTextNode("  ");
         span.appendChild(space);
         if(document.getElementById("history")!=null){
            document.getElementById("history").appendChild(a);
            document.getElementById("history").appendChild(span); 
         }

     }

});


页面

[code]<h4>历史搜索:</h4>
<div id="history"></div>


总结

设置cookie

以分号隔开的键值对组成的字符串赋值给document.cookie。

如:

[code]document.cookie="title=Marry;expires=3600"


读取cookie

因为 cookie 的格式是个个用分号空格分隔,所以用split(‘;’)

[code]var arrCookie = document.cookie ? document.cookie.split('; ') : [];


删除cookie

原理就是设置cookie的expires参数为已经过期的一个时间,第三个参数是多少小时之后过期

[code]setCookie: function(name, value, expiresHours, options){
     var date = new Date();
         date.setTime(date.getTime() + expiresHours * 3600 * 1000);
}


在当前时间的基础上退后几个小时,如果我们要删除cookie,就传一个复数,这样的话过期的时间早于当前时间,说明已经过期啦,一般咱们就传-1就可以啦。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: