在WEB开发中经常要用到cookie,有时候还需要在脚本中用到!
如:在开发天气预报网(http://tqybw.net)中,有这样的需求:当用户查询某个城市天气时,保不刷新页面时需要动态记录用户的访问记录,这时考虑用js脚本cookie!
<script type="text/javascript">
//取得cookie值
function getCookie(name){
var cookieValue = "";
var search = name + "=";
if(document.cookie.length > 0){
offset = document.cookie.indexOf(search);
if (offset != -1){
offset += search.length;
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
cookieValue = unescape(document.cookie.substring(offset, end))
}
}
return cookieValue;
}
//设置cookie值
function setCookie(name, value, hours){
var expire = "";
if(hours != null){
expire = new Date((new Date()).getTime() + hours * 3600000);
expire = "; expires=" + expire.toGMTString();
}
document.cookie = name + "=" + escape(value) + expire;
}
function display_home(value){
name='home_city';
hours=24*10;
setCookie(name, value, hours);
alert('设置成功');
}
</script>
标例:
<div><a href="http://tqybw.net/shenzhen15tian/">深圳天气预报15天</a> <a href="#" onclick="display_home()">设为首页显示</a></div>