Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 仅使用AJAX、HTML5和Jquery创建购物车系统_Javascript_Jquery_Ajax_Html_Cart - Fatal编程技术网

Javascript 仅使用AJAX、HTML5和Jquery创建购物车系统

Javascript 仅使用AJAX、HTML5和Jquery创建购物车系统,javascript,jquery,ajax,html,cart,Javascript,Jquery,Ajax,Html,Cart,我需要创建一个购物车系统,只使用HTML5、AJAX和Jquery,不使用任何服务器端脚本语言(PHP、ASP.NET等) 我的场景是:“一个HTML部门,其中显示添加的产品,包括名称、价格、数量和总计等” 我不知道Jquery将如何与AJAX一起向Div展示产品。有谁能指导我,或者给我一个教程链接,从那里我可以清楚我的概念 这里是仅使用和jQuery在前端视点上实现购物车处理程序的基本方法 <html> <head> <scri

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

我的场景是:“一个HTML部门,其中显示添加的产品,包括名称、价格、数量和总计等”


我不知道Jquery将如何与AJAX一起向Div展示产品。有谁能指导我,或者给我一个教程链接,从那里我可以清楚我的概念

这里是仅使用和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>

$.noConflict();
OODK.config({
“路径”:{
“oodk”:“../src”,
“工作区”:“工作区”
}
});
OODK(函数($,){
$.import({oodk}/foundation/utility/Observable',{oodk}/api/Iteration');
//具有属性名称、单价和id的产品模型
$.class(函数ProductModel($,µ,uUx){
$.protected('id');
$.protected('name');
美元受保护(“价格”);
$.public(函数uu初始化(id、名称、价格){
µ.id=id;
µ.名称=名称;
µ.价格=价格;
});
$.public(函数getId(){
返回µ.id;
});
$.public(函数getName(){
返回µ.名称;
});
$.public(函数getPrice(){
退货价格;
});
});
//购物车项目模型
//cartItem链接到购物车和相关产品
扩展(OODK.Field.UTI.Enviabor).class(函数CARTIMTEMODEL($,γ,)){
美元。受保护(“产品”);
$.protected('qte');
$.protected('cart');
$.public(函数初始化(购物车、产品、qte){
µ.购物车=购物车;
µ.qte=qte;
µ.产品=产品;
});
$.public(函数getCart(){
返回购物车;
});
$.public(函数getProduct(){
退货。产品;
});
$.public(函数设置数量(qte){
返回µ.setObservableProperty('qte',qte,µ);
});
$.public(函数getQuantity(){
返回µ.qte;
});
$.public(函数getPrice(){
返回(µ.qte*µ.product.getPrice());
});
});
//推车模型
//Cart是CartItem的集合
//无论何时添加、删除产品或更改项目数量
//广播一个事件
实现(OODK.Buff.EnvikBaseCaster,OOK.Fask.EnvestListEnter,OODK.Fuff.Eddiable).class(函数CARTMead($,γ,)){
//将指定数量的产品添加到购物车
$.public(函数addProduct(产品,qte){
if(!$.instanceOf(product,us.ns.ProductModel)){
抛出(OOK.Fuff.ILLACALGARMUMETURN异常,‘不能将产品添加到购物车-论证它不是一个有效的产品’)
}
var key=product.getId();
如果(!\u0.hasOwnProperty(键)){
var cartItem=$.new(us.ns.CartItemModel,this,product,qte);
_[键]=项;
var evt=µ.factoryMutableEvent('itemAdded',cartItem);
$触发器(evt);
//侦听对项目所做的更改
美元(cartItem,'propertyChanged',this);
}否则{
var cartItem=U9;[key];
cartItem.setQuantity((cartItem.getQuantity()+1));
}
});
//从购物车中移除产品
$.public(功能移除产品(产品){
if(!$.instanceOf(product,us.ns.ProductModel)){
抛出(OOK.Fuff.ILLACALGARMUMETUN异常,‘不能从CART删除产品-参数不是有效的产品’)
}
var key=product.getId();
if(uuu.hasOwnProperty(键)){
var cartItem=U9;[key];
删除[key];
var evt=µ.factoryMutableEvent('itemRemoved',cartItem);
$触发器(evt);
//停止收听该项目
$.off(cartItem,'propertyChanged',this);
}
});
//计算购物车的总价
$.public(函数getTotalPrice(){
风险价值总额=0.0;
$.forEach(此函数为cartItem,k,i){
if($.instanceOf(cartItem,\ uns.CartItemModel)){
总计+=cartItem.getPrice();
}
});
返回总数;
});
//可变事件的工厂
$.protected(函数factoryMutableEvent(事件类型,模型){
var evt=$.new(u.ns.MutableEvent,eventType,this);
evt.setModel(model);
evt.sync();
evt.可设置可中断(假);
返回evt;
});
//当其中一个cartItem属性更改广播事件时
$.public(函数uu进程事件(evt){
var evtProxy=µ.factoryMutableEvent('propertyChanged',evt.getTarget());
evtProxy.setrcevent(evt);
$.trigger(evtProxy);
});
$.private(函数uu eventconsumered(evt){});
$.private(函数uu dispatchEvent(evt){});
$.private(函数uu approveListener(请求){});
<!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>