1. 程式人生 > >第一種方式:cookie的優化與購物車實例

第一種方式:cookie的優化與購物車實例

bubuko dsi 服務端 stk rtl cal 頁面設置 sset tran

一 Cookie 的優化

1.1 一般而言,我們設置cookie是在php中設置

例如:

<?php
setcookie(‘testKey1‘,‘hello world‘,0,‘/‘); 
//# 當 expires = 0 時,此Cookie隨瀏覽器關閉而失效,
?>

而在驗證的時候,我們通常是:

<?php
if(isset($_COOKIE[‘testKey2‘]))
  echo "The New COOKIE is : testKey2 = ".$_COOKIE[‘testKey2‘];
else
  echo "The new COOKIE is setting failed";
?>

都是在服務端進行。優化:

1.2 在前端頁面進行驗證cookie

cookie保存在客戶端,那麽可以在客戶端那邊進行驗證,根據上面的代碼,前端獲取代碼為:

<script language="JavaScript" type="text/javascript">
var key1 = document.cookie.match(new RegExp("(^| )testKey1=([^;]*)(;|$)")); //正則找出testKey的cookie值
try{
  if(key1[2] != ‘‘)
    document.write("testKey1 = "+key1[2]);
}
catch(e){ document.write("testKey1 = NULL"); };

那麽我們能否在前端設置cookie 呢 ?

1.3 在前端頁面設置cookie【購物車原理】

function setCookie(){
  var expire = new Date(); 
  expire.setTime(expire.getTime() + 86400000);
  document.cookie = "testKey2=This the second Cookie;expires=" + expire.toGMTString() + ";path=/";
  alert(‘完成設置‘);
  location
.href=‘test2.php‘ }

這樣子能夠減輕服務器的壓力

我們要註意,這樣子是有限制的,瀏覽器本身能夠存儲的數據有限:

技術分享圖片

1.4 local storage

在谷歌瀏覽器下,f12可以看到:

技術分享圖片

這個可以看成是瀏覽器的小型數據庫,可以存儲更多的數據。

示例【購物車小試】:

設置頁面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo2</title>
<script language="JavaScript" type="text/javascript">
var cartLSName = ‘abc‘;
//gdsInfo=[ID,NAME,AVATAR,PRICE,NUMBER]
function addToLS(gdsInfo){
  if(!window.localStorage){
    alert(‘您的瀏覽器不支持Local Storage!‘); //如果不支持,可以采用第1.3中的方法
    return false;
  }
  try{
    if(gdsInfo.length != 5){
      alert(‘參數錯誤!‘);
      return false;
    }
  }catch(e){alert(‘參數錯誤!‘);return false}
  var gName=gdsInfo[1];
  gdsInfo[1]=encodeURI(gdsInfo[1]);
  gdsInfo[4]=parseInt(gdsInfo[4]);
  if(isNaN(gdsInfo[4])) gdsInfo[4] = 1;
  //由JSON字符串轉換為JSON對象
  var cartLS = JSON.parse(localStorage.getItem(cartLSName));
  if(cartLS == null){
    cartLS=[gdsInfo];
  }else{
    var existInCart=false;
    for(var i=0;i<cartLS.length;i++){
      if(cartLS[i][0] == gdsInfo[0]){
        cartLS[i][4] += gdsInfo[4];
        existInCart = true;
        break;
      }
    }
    if(!existInCart)
      cartLS.splice(0,0,gdsInfo);
  }
  //將JSON對象轉化為JSON字符,並存入LocalStorage
  localStorage.setItem(cartLSName,JSON.stringify(cartLS));
  return true;
}
</script>
</head>
<body>
<a href="javascript:addToLS([3,‘華為Mate8‘,‘ico.jpg‘,3888.00,2]);" rel="external nofollow" >存儲一</a><br />
</body>
</html>

效果:

技術分享圖片

有設置,就有查看:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Show LocalStorage Info</title>
<script language="JavaScript" type="text/javascript">
if(!window.localStorage){
  alert(‘您的瀏覽器不支持Local Storage!‘);
}
var cartLSName = ‘abc‘;
var cartStr = localStorage.getItem(cartLSName)
//gdsInfo=[ID,NAME,AVATAR,PRICE,NUMBER]
function showStr(){
  str = decodeURIComponent(cartStr);
  alert(str);
  document.getElementById(‘show‘).innerHTML=str;
}
function showInfo(){
  var cartLS = JSON.parse(cartStr);
  if(cartLS == null){
    alert(NULL);
  }else{
    var str = ‘‘;
    for(var i=0;i<cartLS.length;i++){
      str += "ID:"+cartLS[i][0] + "\n";
      str += "Name:"+cartLS[i][1] + "\n";
      str += "Logo:"+cartLS[i][2] + "\n";
      str += "Price:"+cartLS[i][3] + "\n";
      str += "Num:"+cartLS[i][4] + "\n";
    }
    str = decodeURIComponent(str);
    alert(str);
    document.getElementById(‘show‘).innerHTML=str.replace(/\n/g,"<br />");
  }
}
function clearLS(){
  localStorage.clear();
}
</script>
</head>
<body>
<a href="javascript:showStr();" rel="external nofollow" >以字符串形式顯示</a><br />
<a href="javascript:showInfo();" rel="external nofollow" >顯示詳細</a><br />
<a href="javascript:clearLS();" rel="external nofollow" >清空</a><br />
<a href="./" rel="external nofollow" >返回設置頁面</a><br />
<div id="show"></div>
</body>
</html>

效果

以字符串形式顯示

技術分享圖片

顯示詳細

技術分享圖片

以上這篇cookie的優化與購物車實例就是小編分享給大家的全部內容了,希望能給大家一個參考

第一種方式:cookie的優化與購物車實例