【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就可以啦。
相关文章推荐
- moment.js 添加中文语言(汉化)
- 一篇给迷茫者看的JavaScript 引擎指南
- JS判断字符串变量是否含有某个字串的方法
- js模板引擎
- js获取客户时间倒计时,js获取服务器端时间倒计时
- 关于JS变量提升的一些坑
- Gson和Fastjson的使用
- 前端--关于javascript对象
- js定义函数的三种方法
- js调用函数的方法
- berserkJS(大名:狂暴JS / 昵称:疯子JS)
- JS获得URL超链接的参数值
- $.getJSON设置异步请求和同步请求
- js022-高级技巧
- js位置对浏览器加载页面的影响
- js021-Ajax与Comet
- JavaScript 构造函数
- JVM 中的 jps、jinfo、jstat、jstack、jmap、jconsole等命令使用(线程进行分析和故障诊断)
- JavaScript 数组(Array) sort 排序函数实现的简单高阶函数原理
- JavaScript优化(二)