自动刷新价格

在最近学习的经典模块中有使用JavaScript实现购物车自动刷新商品数量和商品价格的功能;经过我的一番研究后把代码整理出来;

由于这个例子中并没有使用到数据库,定义了一个数组作为数据源,代码如下

<?php
    $shopcar=array(
        array("0","手机","20","100","98","9.8"),
        array("1","电脑","25","120","88","9"),
        array("2","汽车","19","200","180","9"),    
        array("3","香蕉","10","2","1.8","9"),    
        array("4","苹果","5","5","4.8","9"),    
    ); 
 ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<table border="0" cellspacing="0" cellpadding="0" align="center">
<form id="myshopcar" name="myshopcar" method="post" action="#">
  <tr>
    <td height="30" colspan="7" align="center" valign="middle" class="first">我的购物车</td>
  </tr>
  <tr>
    <td width="35" height="25" align="center" valign="middle" class="left"> </td>
    <td width="100" height="25" align="center" valign="middle" class="center">商品名称</td>
    <td width="100" height="25" align="center" valign="middle" class="center">购买数量</td>
    <td width="100" height="25" align="center" valign="middle" class="center">市场价格</td>
    <td width="100" height="25" align="center" valign="middle" class="center">会员价格</td>
    <td width="100" height="25" align="center" valign="middle" class="center">折扣率</td>
    <td width="100" height="25" align="center" valign="middle" class="right">合计</td>
  </tr>
  <?php foreach ($shopcar as $key => $value) { ?>  
  <tr>
    <td height="25" align="center" valign="middle" class="left"><input id="chk" name="chk[]" type="checkbox" value="<?php echo $value[0]; ?>"></td>
    <td height="25" align="center" valign="middle" class="center"><div id = "c_name<?php echo $value[0]; ?>">  <?php echo $value[1]; ?></div></td>
    <td height="25" align="center" valign="middle" class="center">
    <input id="cnum<?php echo $value[0]; ?>" name="cnum<?php echo $value[0]; ?>" type="text" class="shorttxt" value="<?php echo $value[2]; ?>" onkeyup="cvp(<?php echo $value[0]; ?>,<?php echo $value[4]; ?>,<?php echo count($shopcar) ?>)"></td>
    <td height="25" align="center" valign="middle" class="center"><div id="m_price<?php echo $value[0]; ?>"> <?php echo $value[3]; ?></div></td>
    <td height="25" align="center" valign="middle" class="center"><div id="v_price<?php echo $value[0]; ?>"> <?php echo $value[4]; ?></div></td>
    <td height="25" align="center" valign="middle" class="center"><div id="fold<?php echo $value[0]; ?>"> <?php echo $value[5]; ?></div></td>
    <td height="25" align="center" valign="middle" class="right"><div id="total<?php echo $value[0]; ?>"> <?php echo $value[2]*$value[4]; ?></div></td>
  <tr>
  <?php } ?>
    <td height="25" colspan="3" align="left" valign="middle">
    <a href="#" onclick="return alldel(myshopcar)">全选</a> <a href="#" onclick="return overdel(myshopcar);">反选</a>  
    <input type="button" value="删除选择" class="btn" style="border-color: #FFFFFF;" onClick = 'return del(myshopcar);'>  </td>
    <td height="25" align="center" valign="middle"><input id="cont" name="cont" type="button" class="btn" value="去数据库修改" onclick="return conshop(myshopcar)" /></td>
    <td height="25" align="center" valign="middle"><input id="uid" name="uid" type="hidden" value="tang" ><input id="settle" name="settle" type="button" class="btn" value="去收银台" onclick="return formset(form)" /></td>
    <td height="25" colspan="2" align="right" valign="middle"><div id='sum'>共计7622 元</div></td>
    </tr>
</form>
</table>    
</body>
</html>

然后是最主要的JavaScript脚本,实现自动刷新的功能代码如下:

实现商品删除代码:

<script>
/*  删除记录  */
function del(form){
    if(!window.confirm('是否要删除数据??')){
        
    }else{
        var leng = form.chk.length;//返回复选框的长度
        if(leng==undefined){
            if(!form.chk.checked){
                    alert('请选取要删除数据!');
            }else{//如果只有一个复选框,而且处于选中状态
                rd = form.chk.value;//将复选框的value值直接赋给变量rd
                var url = 'test.php?rd='+rd;//根据rd生成url
                xmlhttp.open("GET",url,true);
                xmlhttp.onreadystatechange = delnow;//调用delnow函数
                xmlhttp.send(null);
            }
        }else{ //如果复选框为多个
            var rd=new Array();//声明数组
            var j = 0;
            for( var i = 0; i < leng; i++){//循环检查复选框状态
                if(form.chk[i].checked){
                    rd[j++] = form.chk[i].value;//将被选中的复选框的value值存到rd内
                }
            }
            if(rd == ''){
                alert('请选取要删除数据!');
            }else{
                var url = "test.php?rd="+rd;
                alert(url);
                xmlhttp.open("GET",url,true);
                xmlhttp.onreadystatechange = delnow;
                xmlhttp.send(null);
            }
        }
    }
    return false;
}
function delnow(){
    if(xmlhttp.readyState == 4&&xmlhttp.status == 200){
        var msg = xmlhttp.responseText;
        if(msg != '1'){
            alert('删除失败'+msg);
        }else{
            alert('删除成功');
            location=('?page_type=shopcar');
        }
    }
}
//全部选择/取消
function alldel(form){
    var leng = form.chk.length;
    if(leng==undefined){
       if(!form.chk.checked)
               form.chk.checked=true;
     }else{  
       for( var i = 0; i < leng; i++)
        {
            if(!form.chk[i].checked)
                  form.chk[i].checked = true;
        }
     } 
    return false;
}
// 反选
function overdel(form){
     var leng = form.chk.length;
     if(leng==undefined){
       if(!form.chk.checked)
               form.chk.checked=true;
        else
            form.chk.checked=false;
     }else{  
       for( var i = 0; i < leng; i++)
        {
            if(!form.chk[i].checked)
                  form.chk[i].checked = true;
            else
                form.chk[i].checked = false;
        }
     } 
    return false;
}

 实现自动刷新总金额代码:

//自动刷新总金额
// key商品id
// vpr商品单价
// shoparr商品数量
function cvp(key,vpr,shoparr){
    var n_pre = 'total';//获取div标签的id前缀
    var num = 'cnum'+key.toString();//根据key值生成文本域的id值
    var total = n_pre+key.toString();//根据key值生成的div标签的id值
    var t_number = document.getElementById(num).value;//获取输入的商品数量
    var ttl = t_number * vpr;//根据商品数量和单价,计算商品金额
    document.getElementById(total).innerHTML = ttl;//计算商品总金额
    var sm = 0;    //所有商品总金额,初始为0
    for(var i = 0; i < shoparr; i++){//根据商品种类数,循环得到其他商品金额
        var aaa = document.getElementById(n_pre+i.toString()).innerText;
        sm += parseInt(aaa);//将所有商品金额累加
    }
    document.getElementById('sum').innerHTML = '共计:'+sm+' 元';
        
}
//更改商品数量
function conshop(form){
    var n_pre = 'cnum';//获取商品数量文本域前缀
    var lang = form.chk.length;//获取复选框的数量
    if(lang == undefined){//如果只有一个复选框,那么将商品id和商品数量直接保存到变量中
        var fst = form.chk.value;
        var snd = form.cnum0.value;
    }else{//否则将商品id和对应的商品数量保存到两个相应数组中
        var fst= new Array();//商品id数组
        var snd = new Array();//商品数量数组
        for(var i = 0; i < lang; i++){//循环获取复选框的value值和商品数量文本框的value值
            var nm = n_pre+i.toString();
            var stmp = document.getElementById(nm).value; 
            if(stmp  == '' || isNaN(stmp)){
                alert('不允许为空、必须为数字');//对商品数量文本框判断
                document.getElementById(nm).select();
                return false;
            }
            snd[i] = stmp;
            var ftmp = form.chk[i].value;
            fst[i] = ftmp;
        }
    }
    var url = 'test.php?fst='+fst+'&snd='+snd;
    alert(url);
    xmlhttp.open("GET",url,true);
    xmlhttp.onreadystatechange = updatecar;//调用updatecar函数
    xmlhttp.send(null);
}
function updatecar(){//对xmlhttp对象返回值进行处理
    if(xmlhttp.readyState == 4){
        var msg = xmlhttp.responseText;
            if(msg == '1'){
                location='index.php';
            }else{
                alert('操作失败'+msg);
            }
    }
} 

 实现显示订单代码:

// 显示订单
function formset(form){
var uid = form.uid.value;//获取订单提交人的名称
var n_pre = 'cnum';                //商品数量文本前缀
    var lang = form.chk.length;     //复选框个数    
    if(lang == undefined){            // 如果复选框只有一个
        var fst = form.chk.value;            //商品id
        var snd = form.cnum0.value;            //购买数量
    }else{// 如果复选框多个        
        var fst= new Array();
        var snd = new Array();        
        for(var i = 0; i < lang; i++){// 循环获取商品数量和商品id
            var nm = n_pre+i.toString();
            var stmp = document.getElementById(nm).value; 
            if(stmp  == '' || isNaN(stmp)){
                alert('不允许为空、必须为数字');
                document.getElementById(nm).select();
                return false;
            }
            snd[i] = stmp;
            var ftmp = form.chk[i].value;
            fst[i] = ftmp;
        }
    }
    alert('test.php?uid='+uid+'&fst='+fst+'&snd='+snd);
    // open('test.php?uid='+uid+'&fst='+fst+'&snd='+snd,'_blank','width=650 height=300',false);
}
</script>

  

 这里实现数据处理页面的代码参考简单购物车

如在实现商品删除功能代码如下

<?php
session_start(); 
header ( "Content-type: text/html; charset=UTF-8" );                         //设置文件编码格式
require("system/system.inc.php");                          //包含配置文件
/*  xmlhttp返回参数  */
$reback = '0';
/*    将传过来的变量以逗号分割    */
$commid = explode(',',$_GET['rd']);
/*  更新数据库所需数组    */
$newshop = array();
/*    查找当前用户    */
$sql = "select id,shopping from tb_user where name = '".$_SESSION['member']."'";
$rst = $admindb->ExecSQL($sql,$conn);
if($rst==false){
    $reback = '2';
}else{
    /*    将shopping字段用@分割    */
    if(!empty($rst[0]['shopping'])){
        $tmpshop = array();
        $shopping = explode('@',$rst[0]['shopping']);
        foreach($shopping as $ky => $vl){
            $tmp = explode(',',$vl);
            $boo = false;
            foreach($commid as $value){
                if($value == $tmp[0]){
                    $boo = true;
                }
            }
            if(!$boo){
                $tmpshop[$ky] = $vl;
            }
        }
        if(!empty($tmpshop)){
            $update = "update tb_user set shopping='".implode('@',$tmpshop)."' where name = '".$_SESSION['member']."'";
        }else{
            $update = "update tb_user set shopping='' where name = '".$_SESSION['member']."'";
        }
        $shop = $admindb->ExecSQL($update,$conn);
        if($shop){
            $reback = 1;
        }else{
            $reback = 3;
        }
    }
}
echo $reback;
?>

去数据库修改代码如下

<?php
session_start(); 
header ( "Content-type: text/html; charset=UTF-8" );                         //设置文件编码格式
require("system/system.inc.php");                          //包含配置文件
$sql = "select id,shopping from tb_user where name = '".$_SESSION['member']."'";
$rst = $admindb->ExecSQL($sql,$conn);//返回热二维数组
$reback = '0';
$changecar = array();
if(isset($_GET['fst']) && isset($_GET['snd'])){
    $fst = $_GET['fst'];//商品id
    $snd = $_GET['snd'];//商品数量
    $farr = explode(',',$fst);
    $sarr = explode(',',$snd);
    $upcar = array();
    for($i = 0; $i < count($farr); $i++){
        $upcar[$i] = $farr[$i].','.$sarr[$i];
    }
    if(count($farr) > 1){
        $update = "update tb_user set shopping='".implode('@',$upcar)."' where name = '".$_SESSION['member']."'";
    }else{
        $update = "update tb_user set shopping='".$upcar[0]."' where name = '".$_SESSION['member']."'";
    }
    $shop = $admindb->ExecSQL($update,$conn);
    if($shop){
        $reback = 1;
    }else{
        $reback = 2;
    }
}
echo $reback;
?>

代码下载链接 附上一句诗句:海到尽头天作岸,山登绝顶我为峰。加油!

posted @ 2018-04-25 16:09  TangYJun  阅读(225)  评论(0编辑  收藏  举报