ajax在购物车中的应用
Posted 卖女孩的小火柴2号
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ajax在购物车中的应用相关的知识,希望对你有一定的参考价值。
代码如下:
购物车页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>易买网 - 首页</title>
<link type="text/css" rel="stylesheet" href="css/style.css" />
<script type="text/JavaScript" src="scripts/jQuery-1.8.3.min.js"></script>
</head>
<body>
<div id="header" class="wrap">
<div id="logo"><img src="images/logo.gif" /></div>
<div class="help"><a href="shopping.html" class="shopping">购物车X件</a><a href="login.html">登录</a><a href="register.html">注册</a><a href="guestbook.html">留言</a><a href="manage/index.html">后台管理</a></div>
<div class="navbar">
<ul class="clearfix">
<li class="current"><a href="#">首页</a></li>
<li><a href="#">图书</a></li>
<li><a href="#">百货</a></li>
<li><a href="#">品牌</a></li>
<li><a href="#">促销</a></li>
</ul>
</div>
</div>
<div id="childNav">
<div class="wrap">
<ul class="clearfix">
<li class="first"><a href="#">音乐</a></li>
<li><a href="#">影视</a></li>
<li><a href="#">少儿</a></li>
<li><a href="#">动漫</a></li>
<li><a href="#">小说</a></li>
<li><a href="#">外语</a></li>
<li><a href="#">数码相机</a></li>
<li><a href="#">笔记本</a></li>
<li><a href="#">羽绒服</a></li>
<li><a href="#">秋冬靴</a></li>
<li><a href="#">运动鞋</a></li>
<li><a href="#">美容护肤</a></li>
<li><a href="#">家纺用品</a></li>
<li><a href="#">婴幼奶粉</a></li>
<li><a href="#">饰品</a></li>
<li class="last"><a href="#">Investor Relations</a></li>
</ul>
</div>
</div>
<div id="position" class="wrap">
您现在的位置:<a href="index.html">易买网</a> > 购物车
</div>
<div class="wrap">
<div id="shopping">
<form action="address.html">
<table>
<tr>
<th>商品名称</th>
<th>商品价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<?PHP
$userid = 1;//和addCart.php同理,正常情况下可以从session获取到
try{
$pdo = new PDO("MySQL:host=localhost;dbname=lian","root","",array(PDO::ATTR_ERRMODE=>PDO::
ERRMODE_EXCEPTION));
$pdo->query("set names utf8");
$sql = "select p.id,p.title,p.price,c.num from shop_product p right join shop_cart c on p.id=c.productid where c.userid=?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($userid));
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
}catch(PDOException $e){
echo $e->getMessage();
}
?>
<?php
$total = 0;
foreach($data as $product):
?>
<tr id="product_tr">
<td class="thumb"><img src="images/product/0.jpg" /><a href="product-view.html"><?php echo $product[‘title‘]?></a></td>
<td class="price" id="price_id_0">
<span id="price">¥<span id="product_price"><?php echo $product[‘price‘]?></span></span>
<input type="hidden" value="99" />
</td>
<td class="number">
<input id="number_id_0" type="text" name="number" value="<?php echo $product[‘num‘]?>" onblur="changeNum(<?php echo $product[‘id‘]?>,this.value)"/>
</td>
<td class="delete"><a href="javascript:delPro(<?php echo $product[‘id‘]?>)">删除</a></td>
</tr>
<?php
$total+=$product[‘price‘]*$product[‘num‘];
endforeach;
?>
</table>
<div class="total"><span id="total">总计:¥<span id="product_total"><?php echo $total?></span></span></div>
<div class="button"><input type="submit" value="" /></div>
</form>
</div>
<script type="text/javascript">
function changeNum(productid,num){
//通过ajax把参数传给php后台在购物车表中进行商品数量的修改
var url = "changeNum.php";
var data = {"productid":productid,"num":num};
var success = function(response){
if(response.errno == 0){
var total = ($("#number_id_0").val())*($("#product_price").html());
$("#product_total").html(total);
}
}
$.post(url,data,success,"json");
}
function delPro(productid){
//通过ajax把商品id传给PHP后台把购物车表中的数据删除
var total = 0;
var url = "delPro.php";
var data = {"productid":productid};
var success = function(response){
if(response.errno == 0){
$("#product_tr").remove();
$("#product_total").html(total);
}
}
$.get(url,data,success,"json");
}
</script>
<script type="text/javascript">
document.write("Cookie中记录的购物车商品ID:"+ getCookie("product") + ",可以在动态页面中进行读取");
</script>
</div>
<div id="footer">
Copyright © 2013 All Rights Reserved. 京ICP证1000001号
</div>
</body>
</html>
php删除页面:
<?php
//接收,处理参数
$productid = intval($_GET[‘productid‘]);
$userid = 1;
//删除数据
try{
$pdo = new PDO("mysql:host=localhost;dbname=lian","root","",array(PDO::ATTR_ERRMODE=>PDO::
ERRMODE_EXCEPTION));
$pdo->query("set names utf8");
$sql = "delete from shop_cart where productid=? and userid=?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($productid,$userid));
$rows = $stmt->rowCount();
}catch(PDOException $e){
echo $e->getMessage();
}
if($rows){
$response = array(
"errno" => 0,
"errmsg"=> "success",
"data" => true
);
}else{
$response = array(
"errno" => -1,
"errmsg"=> "fail",
"data" => false
);
}
echo json_encode($response);
php添加页面:
<?php
//接收参数
$productid = intval($_POST[‘productid‘]);
$num = intval($_POST[‘num‘]);
//准备向购物车表中添加的数据
$userid = 1;//实际项目中,用户登录后$userid是在session中存着的,这里没有写登录注册页面,就直接定义了
try{
$pdo = new PDO("mysql:host=localhost;dbname=lian","root","",array(PDO::ATTR_ERRMODE=>PDO::
ERRMODE_EXCEPTION));
$pdo->query("set names utf8");
$sql = "select price from shop_product where id=?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($productid));
$data = $stmt->fetch(PDO::FETCH_ASSOC);
$price = $data[‘price‘];
$createtime = time();
//添加(还要判断当前用户在购物车中是否已经加入了该商品,如果已经加入了,只需修改数量即可,如果没加入,再把一条完整数据加入)
$sql = "select * from shop_cart where productid=? and userid=?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($productid,$userid));
$data = $stmt->fetch(PDO::FETCH_ASSOC);
if($data){
$sql = "update shop_cart set num=num+? where productid=? and userid=?";
$params = array($num,$productid,$userid);
}else{
$sql = "insert into shop_cart(productid,num,userid,price,createtime)values(?,?,?,?,?)";
$params = array($productid,$num,$userid,$price,$createtime);
}
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows =$stmt->rowCount();
}catch(PDOException $e){
echo $e->getMessage();
}
//返回最终添加的结果
if($rows){
$response = array(
‘errno‘ => 0,
‘errmsg‘=> ‘success‘,
‘data‘ => true
);
}else{
$response = array(
‘errno‘ => -1,
‘errmsg‘=> ‘fail‘,
‘data‘ => false
);
}
echo json_encode($response);
php修改商品数量页面:
<?php
//接收ajax传过来的参数,准备参数
$productid = intval($_POST[‘productid‘]);
$num = intval($_POST[‘num‘]);
$userid = 1;//正常情况下可以从session中获取到
//更新购物车表的数据
try{
$pdo = new PDO("mysql:host=localhost;dbname=lian","root","",array(PDO::ATTR_ERRMODE=>PDO::
ERRMODE_EXCEPTION));
$pdo->query("set names utf8");
$sql = "update shop_cart set num=? where productid=? and userid=?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($num,$productid,$userid));
$rows = $stmt->rowCount();
}catch(PDOException $e){
echo $e->getMessage();
}
if($rows){
$response = array(
"errno" => 0,
"errmsg"=> "success",
"data" => true
);
}else{
$response = array(
"errno" => -1,
"errmsg"=> "fail",
"data" => false
);
}
echo json_encode($response);
总结如下:
1,ajax起到一种前后台传递数据的中转站作用,页面在不需要刷新的情况下前后台数据交互
2,前台标签元素等调用JavaScript函数,函数中运用ajax向后台传递参数,在jQuery下有三种方式$get(),$post(),$ajax(),$get()和$post()参数含义相同,一参指url,二参指要传递的数据,三参指请求成功后回调的函数,四参指定数据
格式,如json、xml等。$ajax()中要放入一个json对象,也就是用{}扩着,{}内一参指url,二参指要传递的参数,三参
指请求成功后回调的函数,四参指定数据格式,五参指要用何种传输方法,默认是get,可以改成post。回调函数的作用
一般是用来验证是否成功,如果请求成功可以继续操作一些节点改变页面效果。
3,pdo操作数据库
try{
$pdo = new PDO("mysql:host=localhost;dbname=lian","root","",array(PDO::ATTR_ERRMODE=>PDO::
ERRMODE_EXCEPTION));
$pdo->query("set names utf8");
$sql = "delete from shop_cart where productid=? and userid=?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($productid,$userid));
$rows = $stmt->rowCount();
}catch(PDOException $e){
echo $e->getMessage();
}
其中PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION是在设置异常处理模式
三个值得区别如下:
PDO::ERRMODE_SILENT
这是默认使用的模式。PDO会在statement和database对象上设定简单的错误代号,可以使用PDO->errorCode() 和 PDO->errorInfo() 方法检查错误;
PDO::ERRMODE_WARNING
使用这个模式时,PDO将会发出一个传统的E_WARNING信息。
PDO::ERRMODE_EXCEPTION
PDO会抛出一个PDOException异常并设置它的属性来反映错误代号和错误信息。
4,php后台完成查询修改删除增加后要把ajax请求的结果成功与否传回前台
if($rows){
$response = array(
"errno" => 0,
"errmsg"=> "success",
"data" => true
);
}else{
$response = array(
"errno" => -1,
"errmsg"=> "fail",
"data" => false
);
}
echo json_encode($response);
以上是关于ajax在购物车中的应用的主要内容,如果未能解决你的问题,请参考以下文章
Woocommerce:如何在应用/删除优惠券时禁用 AJAX?
ajax 发布请求 - 跨域读取阻塞 (CORB) 阻止跨域响应 CORS