新聞中心
下邊,筆者將帶領(lǐng)大家使用PHP,JQuery和CSS和AJAX技術(shù),去設(shè)計(jì)一個(gè)拖拉式的購物車,這個(gè)購物車的效果比較酷,當(dāng)你選擇好要購買的商品后,直接用鼠標(biāo)拖拉到一個(gè)購物籃的圖標(biāo)中去,則完成一次購物的過程,跟在超市購物的過程有點(diǎn)相像。本文將使用MySQL數(shù)據(jù)庫,并且用到了jQuery中的一個(gè)很好用的插件simpletip(地址:http://craigsworks.com/projects/simpletip/),接下來會(huì)介紹其詳細(xì)的用法。

成都創(chuàng)新互聯(lián)是一家專注于網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站與策劃設(shè)計(jì),北安網(wǎng)站建設(shè)哪家好?成都創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設(shè)十多年,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:北安等地區(qū)。北安做網(wǎng)站價(jià)格咨詢:18982081108
步驟1 建立Mysql數(shù)據(jù)庫
首先,為我們的購物車應(yīng)用建立如下的mysql數(shù)據(jù)庫文件,下面給出表結(jié)構(gòu),并添加一些樣例數(shù)據(jù):
- CREATE TABLE IF NOT EXISTS `internet_shop` (
- `id` int(6) NOT NULL auto_increment,
- `img` varchar(32) collate utf8_unicode_ci NOT NULL default '',
- `name` varchar(64) collate utf8_unicode_ci NOT NULL default '',
- `description` text collate utf8_unicode_ci NOT NULL,
- `price` double NOT NULL default '0',
- PRIMARY KEY (`id`),
- UNIQUE KEY `img` (`img`)
- ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=7 ;
- INSERT INTO `internet_shop` VALUES(1, 'iPod.png', 'iPod', 'The original and popular iPod.', 200);
- INSERT INTO `internet_shop` VALUES(2, 'iMac.png', 'iMac', 'The iMac computer.', 1200);
- INSERT INTO `internet_shop` VALUES(3, 'iPhone.png', 'iPhone', 'This is the new iPhone.', 400);
- INSERT INTO `internet_shop` VALUES(4, 'iPod-Shuffle.png', 'iPod Shuffle', 'The new iPod shuffle.', 49);
- INSERT INTO `internet_shop` VALUES(5, 'iPod-Nano.png', 'iPod Nano', 'The new iPod Nano.', 99);
- INSERT INTO `internet_shop` VALUES(6, 'Apple-TV.png', 'Apple TV', 'The new Apple TV. Buy it now!', 300);
這里我們只是簡單地設(shè)計(jì)了商品的屬性表,其中包括了商品的圖片,名稱,價(jià)格和描述,在實(shí)際的應(yīng)用中,可能會(huì)設(shè)計(jì)更復(fù)雜的商品屬性。
#p#
步驟2 設(shè)計(jì)頁面結(jié)構(gòu)
接下來,我們開始設(shè)計(jì)我們的頁面結(jié)構(gòu),HTML代碼如下:
Shopping cart
The best products at the best prices
- Products
- // 這里動(dòng)態(tài)從數(shù)據(jù)庫中讀取商品
- ?>
- Shopping Cart
![]()
![]()
在這個(gè)頁面中,在上半部分,設(shè)置了一個(gè)div層,用于顯示各種商品,并且在頁面下半部分,另外設(shè)置了一個(gè)用于接收用戶拖拽商品到購物車的層,只要用戶把商品拖拽到這個(gè)層中的任意區(qū)域(不限于拖拽到購物車內(nèi)),都被認(rèn)為是用戶把商品放到了購物車中。
#p#
步驟3 設(shè)計(jì)CSS
將CSS的名稱命名為demo.css,代碼如下:
- body,h1,h2,h3,p,td,quote,small,form,input,ul,li,ol,label{...}{
- /**//* 為某些瀏覽器兼容性而設(shè)計(jì) */
- margin:0px;
- padding:0px;
- font-family:Arial, Helvetica, sans-serif;
- }
- body{...}{
- color:#555555;
- font-size:13px;
- background-color:#282828;
- }
- .clear{...}{
- clear:both;
- }
- #main-container{...}{ /**//* 頁面中主層的寬度和邊距設(shè)置*/
- width:700px;
- margin:20px auto;
- }
- .container{...}{ /**//* 商品列表層和購物車區(qū)域的div設(shè)置 */
- margin-bottom:40px;
- }
- .top-label{...}{ /**//* 這是頁面上部products的樣式*/
- background:url(img/label_bg.png) no-repeat;
- display:inline-block;
- margin-left:20px;
- position:relative;
- margin-bottom:-15px;
- }
- .label-txt{...}{
- background:url(img/label_bg.png) no-repeat top right;
- display:inline-block;
- font-size:10px;
- height:36px;
- margin-left:10px;
- padding:12px 15px 0 5px;
- text-transform:uppercase;
- }
- .content-area{...}{ /**//* content-area區(qū)域的樣式 */
- background:url(img/container_top.png) no-repeat #fcfcfc;
- padding:15px 20px 0 20px;
- }
- .content{...}{
- padding:10px;
- }
- .drag-desired{...}{ /**//* 商品列表區(qū)域的樣式*/
- background:url(img/drag_desired_label.png) no-repeat top right;
- padding:30px;
- }
- .drop-here{...}{ /**//*購物車區(qū)域的樣式 */
- background:url(img/drop_here_label.png) no-repeat top right;
- }
- .bottom-container-border{...}{
- background:url(img/container_bottom.png) no-repeat;
- height:14px;
- }
- .product{...}{ /**//* 商品的樣式 */
- border:2px solid #F5F5F5;
- float:left;
- margin:15px;
- padding:10px;
- }
- .product img{...}{
- cursor:move;
- }
- p.descr{...}{
- padding:5px 0;
- }
- small{...}{
- display:block;
- margin-top:4px;
- }
- .tooltip{...}{ /**//* 商品的簡單介紹用到的樣式,這個(gè)樣式j(luò)Query 的simpletip plugin插件會(huì)用到 */
- position: absolute;
- top: 0;
- left: 0;
- z-index: 3;
- display: none;
- background-color:#666666;
- border:1px solid #666666;
- color:#fcfcfc;
- padding:10px;
- -moz-border-radius:12px; /**//* 圓角效果*/
- -khtml-border-radius: 12px;
- -webkit-border-radius: 12px;
- border-radius:12px;
- }
以上的樣式中給出了關(guān)鍵部分的注釋,其中注意的是使用了CSS3中的圓角效果樣式border-radius,接下來再看剩余的其他樣式部分:
- #cart-icon{...}{ /**//* 購物籃的樣式 */
- width:128px;
- float:left;
- position:relative;
- }
- #ajax-loader{...}{
- position:absolute; /**//* 這是等待加載的圖標(biāo)的樣式*/
- top:0px;
- left:0px;
- visibility:hidden;
- }
- #item-list{...}{ /**//* 購物籃中已放置的商品的樣式*/
- float:left;
- width:490px;
- margin-left:20px;
- padding-top:15px;
- }
- a.remove,a.remove:visited{...}{ /**//* 移除購物車中商品的鏈接的樣式 */
- color:red;
- font-size:10px;
- text-transform:uppercase;
- }
- #total{...}{ /**//* 總計(jì)的樣式*/
- clear:both;
- float:right;
- font-size:10px;
- font-weight:bold;
- padding:10px 12px;
- text-transform:uppercase;
- }
- #item-list table{...}{
- background-color:#F7F7F7;
- border:1px solid #EFEFEF;
- margin-top:5px;
- padding:4px;
- }
- a.button,a.button:visited{...}{ /**//* 結(jié)算按鈕*/
- display:none;
- height:29px;
- width:136px;
- padding-top:15px;
- margin:0 auto;
- overflow:hidden;
- color:white;
- font-size:12px;
- font-weight:bold;
- text-align:center;
- text-transform:uppercase;
- background:url(img/button.png) no-repeat center top;
- }
- a.button:hover{...}{
- background-position:bottom;
- text-decoration:none;
- }
為了兼容IE 6瀏覽器,我們特別添加如下的CSS樣式代碼,以讓IE 6支持PNG下背景透明的特性:
將其中的iepngfix.htc和blank.gif解壓縮到合適的目錄內(nèi),.htc即Html Components,該文件需要在CSS中被調(diào)用;blank.gif是一個(gè)1×1像素的透明GIF圖片。
最后,我們的頁面效果做出來應(yīng)該是這樣的:
#p#
步驟4 PHP部分設(shè)計(jì)
下面進(jìn)行PHP部分的代碼設(shè)計(jì),首先是列出數(shù)據(jù)庫表中的商品,代碼簡單,如下所示:
- Demo.php中
- $result = mysql_query("SELECT * FROM internet_shop");
- while($row=mysql_fetch_assoc($result))
- {
- echo '
';- }
另外一個(gè)需要編寫PHP代碼的地方,是當(dāng)用戶鼠標(biāo)移動(dòng)到某個(gè)商品介紹時(shí),通過jQuery的simpletips插件,將商品的圖片作為參數(shù),使用ajax方式調(diào)用,獲得該商品的介紹,并且返回為一個(gè)HTML文件再給前端頁面進(jìn)行處理,該文件在ajax目錄下的tips.php文件,如下所示:
- Ajax/tips.php
- define('INCLUDE_CHECK',1);
- require "../connect.php";
- if(!$_POST['img']) die("There is no such product!");
- $img=mysql_real_escape_string(end(explode('/',$_POST['img'])));
- $row=mysql_fetch_assoc(mysql_query("SELECT * FROM internet_shop WHERE img='".$img."'"));
- if(!$row) die("There is no such product!");
- echo ''.$row['name'].'
'.$row['description'].'
- price: $'.$row['price'].'
- Drag it to your shopping cart to purchase it';
此外,我們還需要編寫一個(gè)addtocart.php文件,這個(gè)文件的作用是:當(dāng)用戶將選定的商品拖拉到購物車時(shí),程序在數(shù)據(jù)庫中檢索該商品,然后以JSON的形式返回給前端,代碼如下:
- define('INCLUDE_CHECK',1);
- require "../connect.php";
- if(!$_POST['img']) die("There is no such product!");
- $img=mysql_real_escape_string(end(explode('/',$_POST['img'])));
- $row=mysql_fetch_assoc(mysql_query("SELECT * FROM internet_shop WHERE img='".$img."'"));
- echo '{status:1,id:'.$row['id'].',price:'.$row['price'].',txt:\'\
- \
\
\'}';\ \'.$row['name'].' \$'.$row['price'].' \\ \- \
remove \當(dāng)用戶把商品拖拉到購物車區(qū)域后,前端頁面就以表格的形式逐一顯示出用戶所選的商品,如下圖:
最后,我們看下當(dāng)用戶點(diǎn)結(jié)帳按鈕后的頁面order.php的編寫,這里我們只是簡單把用戶的選擇最后羅列出來并且進(jìn)行商品價(jià)格合計(jì),代碼如下:
- define('INCLUDE_CHECK',1);
- require "connect.php";
- if(!$_POST) // 檢查是否有數(shù)據(jù)提交
- {
- if($_SERVER['HTTP_REFERER'])
- header('Location : '.$_SERVER['HTTP_REFERER']);
- exit;
- }
- ?>
- $cnt = array();
- $products = array();
- foreach($_POST as $key=>$value)
- {
- $key=(int)str_replace('_cnt','',$key);
- $products[]=$key; // 將產(chǎn)品的ID編號(hào)放到數(shù)組products中去
- $cnt[$key]=$value;
- $result = mysql_query("SELECT * FROM internet_shop WHERE id IN(".join($products,',').")"); // selecting all the products with the IN() function
- if(!mysql_num_rows($result)) // 沒找到相關(guān)產(chǎn)品
- {
- echo '
There was an error with your order!
';- }
- else
- {
- echo '
You ordered:
';- while($row=mysql_fetch_assoc($result))
- {
- echo '
'.$cnt[$row['id']].' x '.$row['name'].'
';- //計(jì)算總價(jià)格
- $total+=$cnt[$row['id']]*$row['price'];
- }
- echo '
Total: $'.$total.'
';- }
- ?>
這里,使用數(shù)組products保存了用戶選擇好的商品名稱,而cnt數(shù)組則記錄了每個(gè)商品購買的件數(shù),最后實(shí)現(xiàn)效果如下:
#p#
步驟5 jQuery部分設(shè)計(jì)
我們首先要引入相關(guān)的jQuery文件,如下:
同時(shí),我們要編寫自己的script.js文件,在這個(gè)文件中,我們使用了jQuery的toolstip控件:
- var purchased=new Array(); //該數(shù)組包含了用戶購買的商品
- var totalprice=0; //商品總價(jià)
- $(document).ready(function()...{
- $('.product').simpletip(...{ //使用simpletip控件
- offset:[40,0],
- content:'
',
- onShow: function()...{
- var param = this.getParent().find('img').attr('src');
- // 修復(fù)IE6的問題
- if($.browser.msie && $.browser.version=='6.0')
- ...{
- param = this.getParent().find('img').attr('style').match(/src=\"([^\"]+)\"/);
- param = param[1];
- }
- // 通過ajax方式加載tips.php文件
- this.load('ajax/tips.php',...{img:param});
- }
- });
- $(".product img").draggable(...{ // 允許所有商品圖片能拖拽
- containment: 'document',
- opacity: 0.6,
- revert: 'invalid',
- helper: 'clone',
- zIndex: 100
- });
- $("div.content.drop-here").droppable(...{ // 當(dāng)商品被拖拉到購物車區(qū)域時(shí)觸發(fā)
- drop:
- function(e, ui)
- ...{
- var param = $(ui.draggable).attr('src');
- // 修復(fù)IE 6下的問題
- if($.browser.msie && $.browser.version=='6.0')
- ...{
- param = $(ui.draggable).attr('style').match(/src=\"([^\"]+)\"/);
- param = param[1];
- }
- addlist(param); //調(diào)用addlist方法
- }
- });
- });
- 接下來看addlist方法的編寫,其中都提供了詳細(xì)的注釋:
- function addlist(param)
- ...{
- $.ajax(...{ // ajax方法調(diào)用 addtocart.php
- type: "POST",
- url: "ajax/addtocart.php",
- data: 'img='+encodeURIComponent(param), // the product image as a parameter
- dataType: 'json', // JSON形式調(diào)用
- //在調(diào)用前,顯示加載的小圖標(biāo)
- beforeSend: function(x)...{$('#ajax-loader').css('visibility','visible');},
- //調(diào)用成功時(shí)的回調(diào)方法
- success: function(msg)...{
- //調(diào)用成功后,隱藏等待加載的小圖標(biāo)
- $('#ajax-loader').css('visibility','hidden'); // hiding the loading gif animation
- //如果有出錯(cuò)
- if(parseInt(msg.status)!=1)
- ...{
- return false; }
- else
- ...{
- var check=false;
- var cnt = false;
- //檢查某個(gè)商品是否已經(jīng)在購物車中存在了
- for(var i=0; i
- ...{
- if(purchased[i].id==msg.id) ...{
- check=true;
- cnt=purchased[i].cnt;
- break;
- }
- }
- if(!cnt)
- $('#item-list').append(msg.txt);
- if(!check) //如果該商品是新購買商品,購物車中不存在,則purchased數(shù)組中增加相關(guān)產(chǎn)品
- ...{
- purchased.push(...{id:msg.id,cnt:1,price:msg.price});
- }
- else // 如果購物車中已經(jīng)有該商品,則數(shù)量增加
- ...{
- // 這里設(shè)置每樣商品只能買3件,當(dāng)然大家可以修改
- if(cnt>=3) return false;
- //增加購物車中顯示的數(shù)量
- purchased[i].cnt++;
- //設(shè)置數(shù)量下拉框中的數(shù)量
- $('#'+msg.id+'_cnt').val(purchased[i].cnt);
- }
- totalprice+=msg.price; // 重新計(jì)算總價(jià)格
- update_total(); // 修改總價(jià)格
- }
- $('.tooltip').hide(); // 隱藏商品的介紹
- }
- });
- }
- //幫助工具類,找出當(dāng)前產(chǎn)品在purchased數(shù)組中的位置
- function findpos(id)
- ...{
網(wǎng)站題目:AJAX/PHP/JQuery/CSS設(shè)計(jì)拖拉式購物車
本文網(wǎng)址:http://www.dlmjj.cn/article/dpoggjc.html


咨詢
建站咨詢
