zoukankan      html  css  js  c++  java
  • COOKIE的优化与购物车小试

    由于经常被抓取文章内容,在此附上博客文章网址:,偶尔会更新某些出错的数据或文字,建议到我博客地址 :  --> 点击这里

    一 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

    HTML5 提供了两种在客户端存储数据的新方法:

    • localStorage - 没有时间限制的数据存储
    • sessionStorage - 针对一个 session 的数据存储

    之前,这些都是由 cookie 完成的。但是 cookie 不适合大量数据的存储,因为它们由每个对服务器的请求来传递,这使得 cookie 速度很慢而且效率也不高。

    在 HTML5 中,数据不是由每个服务器请求传递的,而是只有在请求时使用数据。它使在不影响网站性能的情况下存储大量数据成为可能。

    对于不同的网站,数据存储于不同的区域,并且一个网站只能访问其自身的数据。

    HTML5 使用 JavaScript 来存储和访问数据。

     在谷歌浏览器下,f12可以看到:

    可以看成是浏览器的小型数据库,可以存储更多的数据。

    更多的关于localStorage相关的,可以看:http://www.w3school.com.cn/html5/html_5_webstorage.asp

    示例【购物车小试】:

    设置页面:

    <!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]);">存储一</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] + "
    ";
                str += "Name:"+cartLS[i][1] + "
    ";
                str += "Logo:"+cartLS[i][2] + "
    ";
                str += "Price:"+cartLS[i][3] + "
    ";
                str += "Num:"+cartLS[i][4] + "
    ";
            }
            str = decodeURIComponent(str);
            alert(str);
            document.getElementById('show').innerHTML=str.replace(/
    /g,"<br />");
        }
        
    }
    
    function clearLS(){
        localStorage.clear();
    }
    
    </script>
    
    </head>
    
    <body>
    <a href="javascript:showStr();">以字符串形式显示</a><br />
    <a href="javascript:showInfo();">显示详细</a><br />
    <a href="javascript:clearLS();">清空</a><br />
    <a href="./">返回设置页面</a><br />
    
    <div style="margin-top:20px;padding:10px" id="show"></div>
    </body>
    </html>

    效果:

    以字符串形式显示

    显示详细

  • 相关阅读:
    adb命令使用总结
    python os.system()和os.popen()
    Source Insight 中文注释为乱码解决办法(完美解决,一键搞定)
    Source Insight 常用设置
    Source Insight 有用设置配置
    Source Insight 常用设置和快捷键大全
    Source Insight 4.0常用设置
    远程桌面中Tab键不能补全的解决办法
    python中if __name__ == '__main__': 的解析
    python os用法笔记
  • 原文地址:https://www.cnblogs.com/zhenghongxin/p/7401545.html
Copyright © 2011-2022 走看看