使用AJAX,HTML5和Jquery创建购物车系统

时间:2016-09-18 14:55:04

标签: javascript jquery ajax html5 cart

我需要使用HTML5,AJAX和Jquery创建购物车系统,并且不需要任何服务器端脚本语言(PHP,ASP.NET等)

我的方案是:“HTML部门将显示添加的产品,包括名称,价格,数量和总计等”

我不知道Jquery如何使用AJAX向Div展示产品。任何人都可以指导我,或者可以给我一个Tutorial链接,从中可以清除我的概念。

2 个答案:

答案 0 :(得分:1)

以下是仅使用OODK-JS和jQuery

的前端视图上的购物车处理程序的基本实现
      <html>
      <head>
      <script src="../src/oodk.js"></script>
      <script src="lib/jquery-1.12.0.min.js"></script>

          <script>

          $.noConflict();

          OODK.config({
            'path': {
              'oodk': '../src',
              'workspace': 'workspace'
            }
          });

          OODK(function($, _){

            $.import('{oodk}/foundation/utility/Observable', '{oodk}/api/Iteration');

            // Model for Product with properties name, unit price and id
            $.class(function ProductModel($, µ, _){

              $.protected('id');

              $.protected('name');

              $.protected('price');

              $.public(function __initialize(id, name, price){
                µ.id = id;
                µ.name = name;
                µ.price = price;
              });

              $.public(function getId(){
                return µ.id;
              });

              $.public(function getName(){
                return µ.name;
              });

              $.public(function getPrice(){
                return µ.price;
              });
            });

            // Model for Cart item
            // a cartItem is linked to the cart and the related product
            $.extends(OODK.foundation.util.Observable).class(function CartItemModel($, µ, _){

              $.protected('product');

              $.protected('qte');

              $.protected('cart');

              $.public(function __initialize(cart, product, qte){
                µ.cart = cart;
                µ.qte = qte;
                µ.product = product;
              });

              $.public(function getCart(){
                return µ.cart;
              });

              $.public(function getProduct(){
                return µ.product;
              });

              $.public(function setQuantity(qte){
                return µ.setObservableProperty('qte', qte, µ);
              });

              $.public(function getQuantity(){
                return µ.qte;
              });

              $.public(function getPrice(){
                return (µ.qte * µ.product.getPrice());
              });
            });

            // Model for Cart
            // Cart is a collection of CartItem
            // whenever a product is added, removed or the quantity of the item changed
            // an event is broadcast
            $.dynamic().implements(OODK.foundation.EventBroadcaster, OODK.foundation.EventListener, OODK.foundation.Iterable).class(function CartModel($, µ, _){

              // add a product to the cart with the specified quantity
              $.public(function addProduct(product, qte){

                if(!$.instanceOf(product, _.ns.ProductModel)){
                  $.throw(OODK.foundation.IllegalArgumentException, 'Cannot add product to cart - argument it is not a valid product')
                }

                var key = product.getId();

                if(!_.hasOwnProperty(key)){

                  var cartItem = $.new(_.ns.CartItemModel, this, product, qte);

                  _[key] = cartItem;

                  var evt = µ.factoryMutableEvent('itemAdded', cartItem);

                  $.trigger(evt);

                  // listen changes made on the item
                  $.on(cartItem, 'propertyChanged', this);
                }else{

                  var cartItem = _[key];

                  cartItem.setQuantity((cartItem.getQuantity()+1));
                }
              });

              // remove a product from the cart
              $.public(function removeProduct(product){

                if(!$.instanceOf(product, _.ns.ProductModel)){
                  $.throw(OODK.foundation.IllegalArgumentException, 'Cannot remove product from cart - argument it is not a valid product')
                }

                var key = product.getId();

                if(_.hasOwnProperty(key)){

                    var cartItem = _[key];

                    delete _[key];

                    var evt = µ.factoryMutableEvent('itemRemoved', cartItem);

                    $.trigger(evt);

                    // stop listening the item
                    $.off(cartItem, 'propertyChanged', this);
                }
              });

              // calculate the total price of the cart
              $.public(function getTotalPrice(){

                var total = 0.0;

                $.forEach(this, function(cartItem, k, i){

                  if($.instanceOf(cartItem, _.ns.CartItemModel)){

                    total += cartItem.getPrice();
                  }
                });

                return total;
              });

              // factory for mutable event
              $.protected(function factoryMutableEvent(eventType, model){

                var evt = $.new(_.ns.MutableEvent, eventType, this);

                evt.setModel(model);

                evt.sync();

                evt.setInterruptable(false);

                return evt;                    
              });

              // when one of the cartItem property change broadcast the event
              $.public(function __processEvent(evt){

                var evtProxy = µ.factoryMutableEvent('propertyChanged', evt.getTarget());

                evtProxy.setSrcEvent(evt);

                $.trigger(evtProxy);
              });

              $.private(function __eventConsumed(evt){});

              $.private(function __dispatchEvent(evt){});

              $.private(function __approveListener(request){});

              $.private(function __iterator(){

                return $.new(OODK.foundation.util.Iterator, this);
              });
            });

            $.extends(OODK.foundation.util.Event).class(function MutableEvent($, µ, _){

                $.private('model');

                $.public(function setModel(model){

                    µ.testConsumed();

                    _.model = model;
                });

                $.public(function getModel(){
                    return _.model;
                });
            });

            // The list view displays the employees as a html table
            $.implements(OODK.foundation.EventListener).class(function CartView($, µ, _){

                // called when an imte is added, removed, or one of the property of the stored model changed
                $.private(function __processEvent(evt){

                    var tmpl;

                    // if the view does not exists yet render it
                    if(jQuery('#cartView').size() === 0){

                      tmpl = '<div id="cartView">';

                      tmpl += '<h4>Cart</h4>';

                      tmpl += '<table id="products">';

                      tmpl += '<thead>';

                      tmpl += '<tr><th>Product</th><th>Quantity</th><th>Price</th></tr>';

                      tmpl += '</thead>';

                      tmpl += '<tbody></tbody>';

                      tmpl += '</table>';

                      tmpl += '<p>Total price: <span class="total-price">0</span></p>';

                      tmpl += '</div>';

                      jQuery("#cartPlaceholder").append(tmpl);
                    }

                    if(evt.getType() === 'propertyChanged'){

                        if(evt.getSrcEvent().getPropertyName() === 'qte'){

                            // the quantity of a cart item product has changed
                            // update the corresponding table cell

                            jQuery('#product-'+evt.getModel().getProduct().getId()+ ' > .cart-item-qte').text(evt.getSrcEvent().getNewValue());

                            jQuery('#cartView .total-price').text(evt.getModel().getCart().getTotalPrice().toFixed(2));

                        }
                    }else if(evt.getType() === 'itemAdded'){

                        // a new product is added to the cart
                        // add a line to the html table

                        tmpl = '<tr id="product-' + evt.getModel().getProduct().getId() + '">';

                        tmpl += '<td class="cart-item-product-name">' + evt.getModel().getProduct().getName() + '</td>';

                        tmpl += '<td class="cart-item-qte">' + evt.getModel().getQuantity() + '</td>';

                        tmpl += '<td class="cart-item-product-price">' + evt.getModel().getProduct().getPrice().toFixed(2) + '</td>';

                        tmpl += '<td><button class="btn-remove-cart-item">X</button></td>';


                        tmpl += '</tr>';

                        jQuery("#cartView > table > tbody").append(tmpl);

                        jQuery('#cartView .total-price').text(evt.getModel().getCart().getTotalPrice().toFixed(2));

                        jQuery('#product-' + evt.getModel().getProduct().getId()).bind('click', function(e){

                          evt.getModel().getCart().removeProduct(evt.getModel().getProduct());
                        });

                    }if(evt.getType() === 'itemRemoved'){

                        // an exsiting product is removed from the cart
                        // delete the corresponding line of the html table

                        jQuery('#product-'+evt.getModel().getProduct().getId()).remove();

                        jQuery('#cartView .total-price').text(evt.getModel().getCart().getTotalPrice().toFixed(2));
                    }
                });
            });

            jQuery(document).ready(function(){

              //instantiate products
              var productApple = $.new(_.ProductModel, 1, "Apple", 0.10);

              var productBanana = $.new(_.ProductModel, 2, "Banana", 0.20);

              var productOrange = $.new(_.ProductModel, 3, "Orange", 0.30);

              //instantiate cart
              var cart = $.new(_.CartModel);

              //instantiate cart view
              var cartView = $.new(_.CartView);

              // bind cart model and view
              $.on(cart, 'itemAdded', cartView);

              $.on(cart, 'itemRemoved', cartView);

              $.on(cart, 'propertyChanged', cartView);

              // add a default product to the cart
              cart.addProduct(productBanana, 2);

              // bind button listeners
              jQuery('#addBananaToCart').bind('click', function(evt){

                  cart.addProduct(productBanana, 1);
              });

              jQuery('#addOrangeToCart').bind('click', function(evt){

                  cart.addProduct(productOrange, 1);
              });

              jQuery('#addAppleToCart').bind('click', function(evt){

                  cart.addProduct(productApple, 1);
              });
            });
          });
          </script>
      </head>
      <body>
        <div id="cartPlaceholder"></div>

      <p>
        <button id="addBananaToCart">add banana to cart</button><br/>
        <button id="addOrangeToCart">add orange to cart</button><br/>
        <button id="addAppleToCart">add apple to cart</button>
      </p>


      </body>
      </html>

答案 1 :(得分:0)

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Shoping cart </h2>
  <div class="row">
<div class="col-md-3">
    <div class="form-group">
      <img name="HP" id="imhp" class="img-thumbnail" src="http://placehold.it/150x150" onclick="addtoCart('imhp');" style="cursor:pointer;">
    </div>
    <div class="form-group">
<p>product small descriptioon</p>
    </div>
    <button type="submit" class="btn btn-default" style="margin: 0 0 15px;" onclick="addtoCart(1);">Add To cart</button>

</div>
<div class="col-md-3">
    <div class="form-group">
      <img name="Dell" id="imdell" class="img-thumbnail" src="http://placehold.it/150x150" onclick="addtoCart('imdell');" style="cursor:pointer;">
    </div>
    <div class="form-group">
<p>product small descriptioon</p>
    </div>
    <button type="submit" class="btn btn-default" style="margin: 0 0 15px;" onclick="addtoCart(2);">Add To cart</button>

</div>
<div class="col-md-3">
    <div class="form-group">
      <img name="sony" id="imsony" class="img-thumbnail" src="http://placehold.it/150x150" onclick="addtoCart('imsony');" style="cursor:pointer;">
    </div>
    <div class="form-group">
<p>product small descriptioon</p>
    </div>
    <button type="submit" class="btn btn-default" style="margin: 0 0 15px;" onclick="addtoCart(3);">Add To cart</button>

</div>
  </div>
</div>
<div class="container">
<div class="jumbotron">
<table class="table" id="tbl">
    <thead>
      <tr>
        <th>Name</th>
        <th>Qty</th>
        <th>Amount</th>
      </tr>
    </thead>
    <tbody id="cartt">
      <tr>
        <td></td>
        <td></td>
        <td></td>

      </tr>
      <button type="submit" class="btn btn-default" style="margin: 0 0 15px;" onclick="clr();">Cancel</button>
    </tbody>

  </table>
  <h3>Sum:</h3> <h2 id = "gttlsum">0</h2>
</div>
</div>
</div>

</body>



<script>
var gttl=0;
var qty =0;
var amount =0;
var naam='';
var recentAdded = '';
//var desc=$('#imhp').attr('name');
function addtoCart(id){
{
if(id=='imhp'){
amount = amount+10;
naam='HP';
}
else if(id=='imdell'){
amount = amount+20;
naam='Dell';
}
else if(id=='imsony'){
amount = amount+30;
naam='Sony';
}

}

qty=qty+1;

var ele= $("#cartt");
gttl = parseInt($("#gttlsum").html());
var isContains = $('#tbl').text().indexOf(naam) > -1;
if(!isContains)
{
ele.append('<tr id="'+naam+'"><td>'+naam+'</td><td id="qty'+naam+'">'+qty+'</td><td id="amount'+naam+'">'+amount+'</td></tr>');
gttl = gttl +amount;
}
else
{
var tqid = '#qty'+naam;
var taid = '#amount'+naam;
var q = $(tqid).html();
var a = $(taid).html();
gttl = gttl +amount;
amount = amount + parseInt(a);
qty = qty + parseInt(q);
var tid = '#'+naam;
var ele= $(tid);
if(ele.html()!='')
{
ele.html('');
ele.append('<td>'+naam+'</td><td id="qty'+naam+'">'+qty+'</td><td id="amount'+naam+'">'+amount+'</td>');
}
else
{
ele.append('<tr id="'+naam+'"><td>'+naam+'</td><td id="qty'+naam+'">'+qty+'</td><td id="amount'+naam+'">'+amount+'</td></tr>');
}
}
$("#gttlsum").html(gttl);
<!-- $('h1').text('NEW...');  -->
naam='';
qty=0;
amount=0;
}


//clear function on Cancel button
function clr()
{
 qty =0;
 amount =0;
 //following line will give a blank HTML on cart DIV
$("#cartt").html('');
$("#gttlsum").html(0);
}
</script>





</html>

尝试此代码并进行探索