-2

两天后我有作业要做。我已经尝试这样做了 4 天,但我无法完成这项工作,所以我想请教您的建议。我尝试的任何事情都不会引导我找到我需要的东西。我正在做一个商店,我已经做了一个登录注册,一个产品展示,但我缺少一件事。

当用户进入产品页面时,他/她可以选择产品的颜色。例如,如果用户想要一部金色 iPhone,然后点击黑色 iPhone 的侧面,该侧面将变为金色。图片应该存储在 MySQL 数据库中,这样当用户点击“立即订购”时,它会显示“黄金 iPhone”。

代码:https ://codeshare.io/UbKVU

我试着至少做回声,这样我就可以把它输入数据库..但没什么。(我知道它的愚蠢想法但是......)

4

1 回答 1

0

好的,这是使用 json 数据管理购物车的客户端部分(您可以通过 php 和 mysql 表创建它。我还将展示 PHP/SQL Schema 方面的内容。

这是 codepen 工作示例:https ://codepen.io/xonosnet/pen/xeoYLz

var checkout = {
  items: [],
  total: 0.00
};

var phones = [
    {
      title: 'iPhone 7',
      model: 'MHCPL6',
      price: 625.22,
      selectedColor: '',
      colors: {
        'White' : '255,255,255',
        'Black' : '0,0,0',
        'Gray'  : '127,127,127',
        'Pink'  : '215,191,191'
      },
      images: {
        'White' : 'https://store.storeimages.cdn-apple.com/4982/as-images.apple.com/is/image/AppleInc/aos/published/images/M/QG/MQGX2/MQGX2?wid=2000&hei=2000&fmt=jpeg&qlt=95&op_usm=0.5,0.5&.v=1516399367562',
        'Black' : 'https://www.att.com/shopcms/media/att/2017/shop/360s/8510273/6166B-1.jpg',
        'Gray'  : 'https://cloud.istyles.com/images/Skins/OSI7P/800/OSI7P-SS-GRY.jpg',
        'Pink'  : 'https://store.storeimages.cdn-apple.com/4982/as-images.apple.com/is/image/AppleInc/aos/published/images/M/QH/MQH22/MQH22?wid=2000&hei=2000&fmt=jpeg&qlt=95&op_usm=0.5,0.5&.v=1516399708457'
      }
    },
      {
      title: 'iPhone 8',
      model: 'DDCNT7',
      price: 785.22,
      selectedColor: '',
      colors: {
        'White' : '255,255,255',
        'Black' : '0,0,0',
        'Gray'  : '127,127,127',
        'Red'  : '225,0,0'
      },
      images: {
        'White' : 'https://s3.envato.com/files/253291200/preview/preview1.jpg',
        'Black' : 'https://img.tvc-mall.com/uploads/details/101112311A-1.jpg',
        'Gray'  : 'https://cloud.istyles.com/images/Skins/OSI7P/800/OSI7P-SS-GRY.jpg',
        'Red'  : 'https://img.tvc-mall.com/uploads/details/101112364C-1.jpg'
      }
    }
  ];

  //Do a post frequest to pull this data out of the DB
  //var phones = get_phones();
  
  $.each(phones, function(index,phone) {
    var phoneColors = get_phone_colors(index); 
    const htmlData = [
      '<div class="phone" data-index="'+index+'">',
      ' <h2>'+phone.title+' <small>('+phone.model+')</small> <span class="price">$'+phone.price+'</span></h2>',
      ' <h4>Choose a color:</h4>',
      ' <div class="color-picker-ctn">',
      '   <div class="color-picker">'+phoneColors.colors+'</div>',
      '   <div class="phone-image" data-model="'+phone.model+'">'+phoneColors.default+'</div>',
      ' </div>',
      ' <button class="add-cart-btn">Add to Cart</button>',
      '</div>'
    ];
    $('.container').append(htmlData.join(''));
  });

function get_phone_colors(i) {
  var p = phones[i],
      data = {
        colors:'',
        default:''
      },
      pass = 0;
  console.log(p);
  $.each(p.colors, function(index,c) {
    var htmlOutput = '<div class="color '+(pass == 0 ? 'color-selected':'')+'" data-key="'+index+'" data-img="'+p.images[index]+'" data-model="'+p.model+'" data-index="'+i+'" style="background-color:rgb('+c+');"></div>';
    console.log('IMG INDEX: '+i);
    data.colors = data.colors+htmlOutput;
    if(pass == 0) {
      phones[i].selectedColor = index;
      data.default = '<img src="'+p.images[index]+'"/>'
    }
    pass = pass+1; 
  });
  return data;
}

function get_phones(phonedata = []) {
  $.post('your_file.php', {get_phones:true}, function(data) {
         phonedata = data;
  },'json');
  return phonedata;
}

$(document).on('click', '.color', function() {
  var model = $(this).data('model'),
      key = $(this).data('key'),
      img = $(this).data('img'),
      index = $(this).closest('.phone').data('index'),
      model = phones[index].model;
  console.log(img);
  console.log("INDEX: "+index);
  phones[index].selectedColor = key;
  $('.color-selected').toggleClass('color-selected');
  $(this).addClass('color-selected');
  $('.phone-image[data-model="'+model+'"]').empty().append('<img src="'+img+'"/>');
});
 

$(document).on('click', '.add-cart-btn', function() {
  var phone = phones[$(this).closest('.phone').data('index')];
  checkout.items.push(phone);
  checkout.total = checkout.total+phone.price;
  
  update_cart();
}); 

var checkout = {
  items: [],
  total: 0.00
};

function update_cart() {
  var htmlOutput = [];
  checkout.total = 0.00;
  if(checkout.items.length > 0) {
    $.each(checkout.items, function(k,v) {
      const output = [
        '<div class="checkout-item">',
        ' <span>'+v.selectedColor+' '+v.title+' ('+v.model+')</span>',
        ' <span>$'+v.price+'</span>',
        '</div>'
      ];
      htmlOutput.push(output.join(''));
      checkout.total = checkout.total+v.price;
    });
    $('.cart').empty().append(htmlOutput.join(''));
    $('.cart').append('<h4>Total: $'+checkout.total.toFixed(2)+'</h4>');
  } else {
    checkout.total = 0.00;
  }
}
.cart {
  display:inline-block;
  width:300px;
  pading:50px;
  vertical-align:top;
}

.container {
  display:inline-block;
  width:auto;
  background-color:rgb(255,255,255); 
  pading:25px;
}
small {
  font-size:14pt;
  font-weight:normal;
}
.price {
  float:right;
}
.phone {
  display:inline-block;
  width:400px;
  height:500px;
  background-color:#FFF;
  border-radius:10px;
  border:2px solid #CCC;
  padding:10px;
  margin:25px; 
}
.color-picker-ctn {
  display:block; 
  width:100%;
  verticle-align:top;
  valign:top;
  background-color:#FFF;
}
.color-picker {
  vertical-align:top;
  display:inline-block;
  width:25%;
}
.phone-image {
  vertical-align:top;
  display:inline-block;
  width:70%;
  border-raidus:15px;
  overflow:hidden;
  background-color:#FFF;
}
.phone-image img {
  border-raidus:15px;
}

.color {
  display:block;
  width:80%;
  height:55px;
  border-radius:5px;
  margin-bottom:5px;
  vertical-align:top;
  valign:top;
  text-align:center;
  border:4px solid rgb(0,0,0,.25);
  transition:all ease 250ms;
}

.color:hover {
  cursor:pointer;
  transition:all ease 250ms;
  border:4px solid rgb(255,0,0);
}
.color-selected {
  border:4px solid rgb(0,255,0)!important;
}


.phone-image img {
  display:block;
  width:100%;
  height:auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cart">
  <p>No items in cart yet.</P>
</div>

<div class="container">
   
  
  
</div>

这是数据库外观的简单表模式。

CREATE TABLE `products` (
  `product_id` int(12) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `model` varchar(50) DEFAULT NULL,
  `price` decimal(6,2) DEFAULT '0.00',
  PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE `product_colors` (
  `option_id` int(12) NOT NULL AUTO_INCREMENT,
  `product_id` int(12) NOT NULL,
  `color_name` varchar(50) NOT NULL,
  `color_rgb` varchar(11) DEFAULT '255,255,255',
  `color_img` text,
  `additional_cost` decimal(6,2) DEFAULT '0.00',
  PRIMARY KEY (`option_id`),
  KEY `product_id` (`product_id`),
  CONSTRAINT `product_colors_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `products` (`product_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

最后,这是处理 PHP 方面的一种简单快速且肮脏的方法。我没有包含有关如何建立数据库连接的说明(在此示例中,我通过 $conn 调用它。如果您不知道如何建立 PDO Mysql 连接,请查看如何建立 PDO Mysql 连接。

<?php
    if(isset($_POST['get_phones']) {
        $json = get_phones();
        echo json_encode($json, JSON_PRETTY_PRINT);
    }

    function get_phones($return = array()) {
        global $conn; //Your mysql connection object (using PDO)
        $query = 'SELECT p.product_id, p.title, p.model, p.price FROM products as p';
        $stmt = $conn->prepare($query);
        $stmt->execute();
        $rc = $stmt->rowCount();
        if($rc > 0) {
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $colors = get_product_colors($row['product_id']);
                $return[] = $row;
                $return['colors'] = $colors['colors'];
                $return['img'] = $colors['img'];
            }
        }
        return $return;
    }

    function get_product_colors($pid, $return = array('colors'=>array(), 'img'=>array())) {
        global $conn;
        $query = 'SELECT p.option_id, p.color_name, p.color_rgb, p.color_img FROM product_colors as p WHERE p.product_id = '.$pid;
        $stmt = $conn->prepare($query);
        $stmt->execute();
        $rc = $stmt->rowCount();
        if($rc > 0) {
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $return['colors'][$row['color_name']] = $row['color_rgb'];
                $return['img'][$row['color_name']] = $row['color_img'];
            }
        }
        return $return;
    }
?>
于 2019-05-01T23:33:44.190 回答