开发者

saving and setting how far a web page has scrolled down

I'm building a shopping kart in PHP. At the moment the user will hit a button "add to cart" to add an item. that button will then run a seperate php script to save the item in the cart and then the user is returned to the shopping page. all the user sees is the page scrolling back up to the top of the screen.

Is there a 开发者_运维百科way in php that i can save how far the page has scrolled down and then set it when the page is reloaded so that it appears to the user that the page hasn't changed... Thanks


Has to be done in the browser using some javascript. get the position before the submit from var top = window.scrollTop and convey that to server (or store in a cookie) then at load time call window.scrollTo(top) to restore position.


From the sound of it, I think you would be better off using AJAX to submit the product to the cart. That way the user clicks the link and you can pop a little message that changes the cart total after saving it, and the user doesn't have to fully reload the page.

If you are using jQuery something like the following should work: (Not tested)

$('.add-to-cart').click(function(){
     $.ajax({
          url:'cart.php?product=' + sku,
          success:function(){
               // Change the cart total and pop a message here
          }
     });
});


Without using AJAX:

browse.php:

<form action="cart.php" method="POST">
  <div id="product_12345">
      <!-- Product Info -->
      <button name="add_item" type="submit" value="12345">Add To Cart</button>
  </div>
  <div id="product_12346">
      <!-- Product Info -->
      <button name="add_item" type="submit" value="12346">Add To Cart</button>
  </div>
</form>

cart.php:

<?php
if (isset($_POST['add_item'])) {
    // code to add product to cart
    header('Location: /browse.php#product_' + (int)$_POST['add_item']);
}
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜