购物车:饼干只能容纳2至5件物品

时间:2013-07-11 22:08:52

标签: javascript variables cookies session-cookies shopping-cart

对于拥有javascript技能的人来说,这可能是一个简单的修复(轻松+200声誉)。

问题演示:http://shoppingcart-bthub.blogspot.com/只需将所有商品添加到购物车,然后点击刷新即可查看Cookie的问题。

一切正常,除了处理添加到购物车的商品的Cookie的代码部分。出于某种原因,它只能容纳2到5个项目,具体取决于broswer:

谷歌浏览器 - 仅包含2项(购物车中的所有其他项目在页面重新加载后消失)

Firefox - 总共4项

Safari - 4

Internet Exploer - 5

演示中的javascript: http://shopppingcart.googlecode.com/files/simplecart.js

上面的javascript链接部分用于处理Cookie:

    /*** data storage and retrival ****/ 
/* load cart from cookie */ 
me.load = function () {
var me = this;
 /* initialize variables and items array */
me.items = {};
me.total = 0.00;
me.quantity = 0;

 /* retrieve item data from cookie */
if( readCookie('simpleCart') ){
var data = unescape(readCookie('simpleCart')).split('++');
for(var x=0, xlen=data.length;x<xlen;x++){
var info = data[x].split('||');
var newItem = new CartItem();   
if( newItem.parseValuesFromArray( info ) ){
newItem.checkQuantityAndPrice();

/* store the new item in the cart */
 me.items[newItem.id] = newItem;
 }
 }
 }
 me.isLoaded = true;
};

/* save cart to cookie */
me.save = function () {
var dataString = "";
for( var item in this.items ){
dataString = dataString + "++" + this.items[item].print();
}
createCookie('simpleCart', dataString.substring( 2 ), 30 );
};

测试完整的实时代码:

对于包含所有代码的完整实时模板,请在blogger.com上打开免费博客并在此处下载XML模板以上传到博主:http://www.bloggermint.com/2011/05/shopping-cart-blogger-template/免费下载位于左侧边栏。也请按照该页面上的说明进行操作,以便在blogger.com中进行操作

2 个答案:

答案 0 :(得分:6)

在我看来,问题与4K cookie大小限制有关 您的shopppingcart代码正在尝试将所有商品数据存储在simpleCart Cookie中,但是当此类数据大于4K时,这些商品不会存储到Cookie中,即使它们已在购物车中显示因此,当页面重新加载时,这些项目就会消失 例如,考虑网站http://shoppingcart-bthub.blogspot.in/,特别是“Sony VAIO laptop”项目的HTML标记:

<table border="1" style="width: 660px;">
    <tbody>
        <tr>
            <th class="item_thumb" id="thumb" width="45%"><img border="0" src="http://3.bp.blogspot.com/-LcQD--Bb_YE/TeDI44AmUsI/AAAAAAAACBw/K4IJZE2CpMY/s1600/sony+vaio.JPG"></th>
            <td>
                <input class="item_add" type="button" value="Add to Cart" id="s1">
            </td>
        </tr>
        <tr>
            <th><b>Item Name</b></th>
            <td class="item_name">Sony VPCEE42FX 15.5" 2.30GHz 500GB VAIO Laptop</td>
        </tr>
        <tr>
            <th><b>Price</b></th>
            <td class="item_price">$610.00</td>
        </tr>
        <tr>
            <th><b>Description</b></th>
            <td class="item_Description">
            The VPCEE42FX is big enough to be useful, but small 
            enough to be portable. With 500GB of hard drive space, youll have to work hard 
            to fill up the memory. The 15.5 HD resolution screen and AMD Mobility Radeon HD 
            graphics card ensure that youll see crisp, fast action, even when youre watching 
            DVDs on the DVD drive. And at under six pounds, the laptop is easy to pack up 
            and haul with you.
            </td>
        </tr>
        <tr>
            <th><b>Available Stock</b></th>
            <td>2 more available</td>
        </tr>
    </tbody>
</table>

将此产品添加到购物车后,simpleCart Cookie将包含以下字符串:

  

ID = C10 ||拇指=%3Cimg%20border%3D%220%22%20src%3D%22http%3A // 3.bp.blogspot.com / -LcQD - Bb_YE / TeDI44AmUsI / AAAAAAAACBw / K4IJZE2CpMY / S1600 /索尼+ vaio.JPG%22%3E%0A ||名称=索尼%20VPCEE42FX%2015.5%22%202.30GHz%20500GB%20VAIO%20Laptop ||价格= 610 ||描述=的%20VPCEE42FX%图20是%20big% 20enough%20to%20be%20useful%2C%20but%20small%20enough%20to%20be%20%0Aportable。%20With%20500GB%20of%20hard%20drive%20space%2C%20youll%20have%20to%20work%20hard%20to %20%0Afill%20up%第二十条%20memory。%第二十条%2015.5%20HD%20resolution%20screen%20于是%20AMD%20Mobility%20%0ARadeon%20HD%20graphics%20card%20ensure%20that%20youll%20see%20crisp%2C% 20fast%20action%2C%20even%20%0Awhen%20youre%20watching%20DVDs%20on%第二十条%20DVD%20drive。%20于是%20AT%20under%20six%20pounds%2C%第二十条%20%0Alaptop%图20是%20easy%20to %20pack%20up%20于是%20haul%20with%20you。||量= 1

如您所见,似乎所有<td>个名称以item_开头的元素都存储在Cookie中。
Chrome开发者的工具显示此Cookie的大小为828字节 因此,可添加到购物车的商品数量是可变的,取决于每个商品数据的长度(名称,描述等)。
那么,你能做些什么来避免这个问题?

  1. 将项目HTML标记降至最低,例如删除item_thumbitem_Description元素。
  2. 修改addToCart代码中的simplecart.js方法,通过存储更少的信息来减少cookie的长度(详见下文)。
  3. 修改createCookie代码中的readCookieeraseCookiesimplecart.js函数,使用local storage代替Cookie来存储商品数据(看一看)在this page获取代码示例,或在下面获取另一个示例。)
  4. 例如,为避免在Cookie中存储“thumb”和“Description”项目字段,您可以按如下方式修改addToCart方法:

    ShelfItem.prototype.addToCart = function () {
      var outStrings = [],valueString;
      for( var field in this ){
        if( typeof( this[field] ) != "function" && field != "id" ){
          valueString = "";
    
          //console.log(field);
          switch(field){
            case "price":
              if( this[field].value ){
                valueString = this[field].value;
              } else if( this[field].innerHTML ) {
                valueString = this[field].innerHTML;
              }
              /* remove all characters from price except digits and a period */
              valueString = valueString.replace( /[^(\d|\.)]*/gi , "" );
              valueString = valueString.replace( /,*/ , "" );
              break;
            case "image":
              valueString = this[field].src;
              break;
            case "thumb":
            case "Description":
            case "description":
              /* don't store "thumb" and "description" in the cookie */
              break;
            default:
              if( this[field].value ){
                valueString = this[field].value;
              } else if( this[field].innerHTML ) {
                valueString = this[field].innerHTML;
              } else if( this[field].src ){
                valueString = this[field].src;
              } else {
                valueString = this[field];
              }
              break;
          }
          outStrings.push( field + "=" + valueString );
        }
      }
    }
    

    更好的方法是在浏览器支持时使用localStorage,否则使用Cookie作为后备:

    function supports_html5_storage() {
      try {
        return 'localStorage' in window && window['localStorage'] !== null;
      } catch (e) {
        return false;
      }
    }
    
    function createCookie(name,value,days) {
      if (supports_html5_storage()) {
        if (value == '') {
          eraseCookie(name);
        } else {
          window.localStorage.setItem(name, JSON.stringify(value));
        }
      } else {
        if (days) {
          var date = new Date();
          date.setTime(date.getTime()+(days*24*60*60*1000));
          var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
      }
    }
    
    function readCookie(name) {
      if (supports_html5_storage()) {
        return window.localStorage.getItem(name);
      } else {
        var ca = document.cookie.split(';');
        var nameEQ = name + "=";
        for(var i=0;i < ca.length;i++) {
          var c = ca[i];
          while (c.charAt(0)==' ') c = c.substring(1,c.length);
          if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
      }
    }
    
    function eraseCookie(name) {
      if (supports_html5_storage()) {
        window.localStorage.removeItem(name);
      } else {
        createCookie(name,"",-1);
      }
    }
    

    使用localStorage时,我们也可以毫无问题地存储thumbdescription字段(因为我们有5 Mb的空间),因此我们可以进一步修改ShelfItem.prototype.addToCart以这种方式运作:

      ...
      case "thumb":
      case "Description":
      case "description":
        if (!supports_html5_storage()) break;
      ...
    

答案 1 :(得分:1)

看来你正在黑暗的房间里捕捉黑猫而且猫不在那里。

所以我做了什么:

  1. 获取http://shopppingcart.googlecode.com/files/simplecart.js
  2. http://wojodesign.com/simpleCart/
  3. 获取HTML
  4. 将simplecart.js替换为您的。
  5. 我发现了什么:

    1. 当您从文件系统打开html页面时,您拥有了所拥有的内容
    2. 如果你把它放在服务器上(在我的情况下是apache的本地实例)那么一切正常
    3. 2集。

      您尝试在Cookie中提供大量信息。 简单的方法就像这样修改打印功能

      CartItem.prototype.print = function () {
          var returnString = '';
          for( var field in this ) {
            if( typeof( this[field] ) != "function" && field !="description") {
              returnString+= escape(field) + "=" + escape(this[field]) + "||";
            }
          }
          return returnString.substring(0,returnString.length-2);
        };
      

      你真的需要cookie中的所有项目字段吗?