JavaScript操作Cookie实现“历史搜索”

来源:互联网 发布:p社 mac 编辑:程序博客网 时间:2024/05/17 09:01

原文地址:http://blog.csdn.net/u010924834/article/details/50544284

导读

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

一睹为快

        搜索页 
                  【搜索页】 
        这里写图片描述 
                 【搜索结果页】

需求

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

实现思路

  用户通过点击热门搜索、历史搜索中的关键字或者是在搜索框输入关键字之后点击搜索按钮都会进入到搜索结果页面。所以,我们的思路是: 
  当搜索结果页面加载完毕时,将关键字和关键字对应的链接地址存起来,当搜索页重新加载时,将保存的记录显示到界面上。

代码

公共js

/** * 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;    }};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126

调用添加历史记录的方法

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, "");    }}       
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

显示历史记录到页面上

$(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);          }     }});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

页面

<h4>历史搜索:</h4><div id="history"></div>
  • 1
  • 2

总结

设置cookie

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

document.cookie="title=Marry;expires=3600"
  • 1

读取cookie

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

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

删除cookie

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

setCookie: function(name, value, expiresHours, options){     var date = new Date();         date.setTime(date.getTime() + expiresHours * 3600 * 1000);}
  • 1
  • 2
  • 3
  • 4

在当前时间的基础上退后几个小时,如果我们要删除cookie,就传一个复数,这样的话过期的时间早于当前时间,说明已经过期啦,一般咱们就传-1就可以啦。

原创粉丝点击