简体   繁体   中英

Using localStorage to pass data between different pages

I have a shopping basket where i want a user to be able to click on a button that takes them to a separate page whilst capturing their shopping basket contents (item names, quantities, prices, etc). At the moment i'm using localStorage to send just the item names to my new page however the only item that ever prints is the last item to be placed in a basket (i'm not sure how to stop localStorage overwriting data like it does).

This is the itemName section on the basket page.

<!--START: itemnamelink--><a id="itemName" href="product.asp?itemid=[ITEM_CATALOGID]">[ITEM_NAME]</a><!--END: itemnamelink-->

This is a script i have on my basket page.

      jQuery( document ).ready(function($) {
    var itemName = document.getElementById('itemName');


       var arrayShop = [{name: itemName.textContent}];

if(localStorage.getItem("user") == null) { 
 localStorage.setItem("user",JSON.stringify([arrayShop]))
}
else{
  var newArray = JSON.parse(localStorage.getItem("user"));
  newArray.push(arrayShop);
  localStorage.setItem("user", JSON.stringify(newArray))
}


});

This is the script on a new page

 jQuery( document ).ready(function($) {

var hst = document.getElementById("add");

console.log(localStorage.getItem("user"));

var items = JSON.parse(localStorage.getItem("user"));

   for (var i = 0; i < items.length; i++) {
 hst.innerHTML += "<tr><td>" + items[i].name + "</td><td>"+ items[i].price + 

"</td></tr>";
}





});

 <!--HTML ON THE PAGE -->


    <table id="add">
    <tr><td>Name</td><td>Price</td></tr>
</table>

I'm getting the following output which is the last item in the basket (there's 4 items in the basket).

Name    
110mm Chair 

I should be getting.

Name
110mm Chair
Red Chair
Green Chair
Grey Chair

Below is my shopping cart

 <div class="shoppingCartItems">
      <div class="titles2">
        <div class="item-info">[shoppingcart_items]</div>
        <div class="item-qty">[shoppingcart_quantity]</div>
        <div class="item-price">[shoppingcart_price]</div>
        <div class="item-total">[shoppingcart_total]</div>
        <div class="item-remove">&nbsp;</div>
        <div class="clear"></div>
      </div>
      <!--START: SHOPPING_CART_ITEM-->
      <div class="row">
        <div class="item-info">
          <div class="product-image"><!--START: itemthumbnail--><a href="product.asp?itemid=[ITEM_CATALOGID]"><img src="thumbnail.asp?file=[THUMBNAIL]" height="55" width="55" /></a><!--END: itemthumbnail--><!--START: thumbnailnolink--><img src="thumbnail.asp?file=[THUMBNAIL]" height="55" width="55" id="tnl" /><!--END: thumbnailnolink--></div>
          <div class="product-name-options"> 
            <!--START: itemnamelink--><a id="itemName" class ="itemName" href="product.asp?itemid=[ITEM_CATALOGID]">[ITEM_NAME]</a><!--END: itemnamelink--> 
            <!--START: itemnamenolink--><span id="spnItemName">[ITEM_NAME]</span><!--END: itemnamenolink--> 
            <!--START: itemoptions--> 
            <br />
            <a href='#' onclick="toggle('opt[ITEM_ID]')">View/Hide options</a><br />
            <div id=opt[ITEM_ID] name=opt[ITEM_ID] style="display:none;">[OPTIONS]</div>
            <!--END: itemoptions--> 
            <!--START: recurring_frequency-->
            <div class="recurring_frequency">This item will Autoship every <strong>[recurring_frequency]</strong></div>
            <!--END: recurring_frequency--> 
            <!--START: giftwraplink-->
            <div class="giftwraplink"> <a onclick="showGiftWrap('[ITEM_ID]')">[giftwrap_link]</a> </div>
            <!--END: giftwraplink--></div>
          <div class="clear"></div>
        </div>
        <div class="item-qty">
          <input type="text" name="qtyitemnum" value="[ITEM_QUANTITY]" size="3" maxlength="5" class="txtBoxStyle" />
          <input type="hidden" name="coliditemnum" value="[ITEM_ID]" size="3" maxlength="5" />
          <a href="#" onclick="document.forms['recalculate'].submit();return false;" class="update-qty">[shoppingcart_updatecart]</a>
        </div>
        <div class="item-price" id="itemPrice">[ITEM_PRICE] </div>
        <div class="item-total">[ITEM_SUBTOTAL]</div>
        <div class="item-remove"><a href="#" onclick="document.recalculate.qtyitemnum.value=0;document.recalculate.submit();"><i class="icon-cancel"></i></a></div>
        <div class="clear"></div>
      </div>
      <!--END: SHOPPING_CART_ITEM-->
      <div class="shoppingCartTotal">
        <div class="clear">&nbsp;</div>
        <div class="item-total">[CARTSUBTOTAL]</div>
        <div class="item-price">[shoppingcart_subtotal]</div>
        <div class="clear"></div>
        <!--START: DISCOUNTS-->
        <div class="clear">&nbsp;</div>
        <div class="item-total">[DISCOUNTS]</div>
        <div class="item-price">[checkout1_discounts]</div>
        <div class="clear"></div>
        <!--END: DISCOUNTS-->
        <div class="clear">&nbsp;</div>
        <div class="item-total"><strong>[CARTTOTAL]</strong></div>
        <div class="item-price"><strong>[shoppingcart_total]</strong></div>
        <div class="clear"></div>
      </div>
    </div>

I am not getting your shopping cart properly how you are doing it. but using below code as the reference you can solve your problem.

var uname = document.getElementById('uname1').value;

function checkFname(){
    var fname = document.forms["form"]["fname"].value;
    var chk_fname = fname.replace(/^[a-zA-z]{2,15}$/, '');
    if (fname != chk_fname) {
        document.getElementById("fname").className = '';
        return true;
    } 
    else if (fname == chk_fname) {
        document.getElementById("fname").className = 'error';
        return false;
    }
}


function Register(){
    var uname = document.getElementById('uname').value;
    var user = {
        'fname':document.getElementById('fname').value,
        };
    localStorage.setItem(uname,JSON.stringify(user));
}
function Validate(){
    Register();
}

While inserting the data in local storage Register() function will take the username as key and user can be an array which can contain data.

That it is because you are overwriting, not adding. In your code you need to append elements to your storage, using your last record and adding the new one, like this:

var arrayShop = {name: 'Chair 2'};
if(localStorage.getItem("user") == null) { 
 localStorage.setItem("user",JSON.stringify([arrayShop]))
}
else{
  var newArray = JSON.parse(localStorage.getItem("user"));
  newArray.push(arrayShop);
  localStorage.setItem("user", JSON.stringify(newArray))
}

In this example my 'Chair 1' is your new element to add, soo if you execute it two times it will add a new element that is what passed in arrayShop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM