商城项目:商品列表ajax加载,ajax加入购物车

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ProductLists.aspx.cs" Inherits="Hidistro.UI.Web.Vshop.ProductLists" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, viewport-fit=cover" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta name="format-detection" content="telephone=no" />
    <title>商品列表</title>
    <link href="../ziyuan/css/css.css" rel="stylesheet" />

    <script src="../ziyuan/js/jquery-2.2.4.min.js"></script>
    <script src="../ziyuan/js/jquery.SuperSlide.2.1.1.js"></script>
    <script src="../ziyuan/js/main.js"></script>
    <script src="../Utility/common.js"></script>
</head>
<body>
    <header><a href="JavaScript:History.back(-1);" class="b-back" style="display:none"></a><a href="#" class="b-share"></a><a href="#" class="b-heart"></a></header>
    <section>
        <div class="b-top">
            <div class="b-logo">
                <img src="/ziyuan/images/b-logo.png"></div>

            <div class="b-name"><span id="sp1">
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            </span></div>
            <div class="b-star border-r">
                <span><em></em></span><span><em></em></span><span><em></em></span><span><em></em></span><span></span><i>
                    <%=storeScore%> </i>
            </div>
            <div class="b-bas border-r">60分钟送达</div>
            <div class="b-bas">基础运费6元</div>
            <br />
            <div class="b-score">
                <em></em>
                <span><%=firstraceScore%>%</span>
            </div>
        </div>
        <div class="b-news" style="display:none">
            <div class="txtScroll-top">
                <div class="hd">
                    <a class="next"></a>
                    <ul>
                    </ul>
                    <a class="prev"></a><span class="pageState"></span>
                </div>
                <div class="bd" >
                    <ul class="infoList">
                        <li><a href="#">店庆大优惠,回馈新老客户 限时满100-20,先到先得!</a></li>
                        <li><a href="#">店庆大优惠,回馈新老客户 限时满100-20,先到先得!店庆大优惠,回馈新老客户 限时满100-20,先到先得!</a></li>
                    </ul>
                </div>
            </div>
            <script id="jsID" type="text/javascript">
                jQuery(".txtScroll-top").slide({ titCell: ".hd ul", mainCell: ".bd ul", autoPage: true, effect: "topLoop", autoPlay: true, delayTime: 1000, interTime: 4000 });
            </script>

        </div>
          <div class="b-search border-b2">
    <input id="search1" type="text" placeholder="搜索店内商品"/>
     
  </div>
        <%--    <div class="b-search border-b2">
         <input type="text" name="keyWord" id="" value="" placeholder="请输入商品关键字"/>
       <button id="search1" type="button" value="" ></button>
    </div>--%>
 <%--       <script type="text/javascript">function searchs(v) { var url = "ProductList?keyWord=" + v; window.location.href = url; }</script>
        <form onsubmit="searchs(escape(($(this).find(':text').eq(0).val()))); return false;">
            <div class="members_con">
                <section class="members_search">
                    <input type="text" name="keyWord" id="" value="" placeholder="请输入商品关键字">
                    <button type="button" value="" onclick="searchs(escape($($(this).prev()).val()))"></button>
                </section>
            </div>
        </form>--%>
        <div class="b-tab border-b2">
            <ul class="clearfix">
                <li class="active border-r2"><a href="#">商品</a></li>
                <li><a id="aa1">评价</a></li>
            </ul>
        </div>
        <div class="wx_wrap">
            <div class="main">
                <input type="hidden" id="token" name="weiphp" value="" />
                <div class="yScroll1">
                    <ul class="category1" id="categoryli1">
                        <%--<li class="cur">干果</li>
        <li class="">水果 </li>
        <li class="">蔬菜</li>
        <li class="">日用品</li>
        <li class="">家庭用品</li>
      </ul>--%>
                        <asp:Repeater ID="Repeater1" runat="server">
                            <ItemTemplate>
                                <li class="" id="<%# Eval("CategoryId")%>"><%# Eval("Name")%></li>
                            </ItemTemplate>
                        </asp:Repeater>
                    </ul>
                </div>
                <div class="yScroll2Title"></div>
                <div class="yScroll2 js-yScroll2">

                    <div class="yScroll2Div" style="padding: 0 0 50px 0;">

                        <dl class="category2">

                            <div class="book1" id="goods_list">
                                <dd>

                                    <div class="book1Content js-book1Content1 js-book1ContentBtn" id="ulMsgs">

                                        <%-- <asp:Repeater ID="Repeater2" runat="server">
                      <ItemTemplate>
                           <div class="ddd" >
                <div class="book1ConLoop1 border-b2" >
                  <div class="contfl1"><img src="/ziyuan/images/b-img1.png"><div class="img_bg"></div></div>
                  <div class="contCent1 contCent2">
                    <p class="sketch" id="<%# Eval("ProductId")%>"> 
                        <%# Eval("ProductName")%>

                    </p>
                    <p class="text">评价 213条  |  已售 231</p>
                    <p class="price"><span class="js-unitCost"> <%# Eval("SalePrice")%></span> <s>/斤</s></p>
                    <p class="scor">首溯评分<i>4.3</i></p>
                  </div>
                  <div class="contfr2 js-contfr2">
                    <div class="btn js-disabled" style=""></div>
                    <div class="ChangeNum js-disabled"  style="display: none;">
                      <div class="text"><span class="number">1</span></div>
                      <div class="plusMinus js-plusMinus">
                        <div class="plus"></div>
                        <div class="minus"></div>
                      </div>
                    </div>
                  </div>
                </div>
                               </div>
                          </ItemTemplate>
                  </asp:Repeater>--%>
                                    </div>

                                </dd>
                            </div>
                        </dl>
                    </div>
                </div>
                <div class="book1Footer js-book1Footer" id="dddd1">
                    <ul class="bookFoot">
                        <li class="shop" id="shop1"><span class="no-shop">购物车是空的</span><span style="display: none;" class="has-price"><i class="js-num">0.00</i></span></li>
                        <li class="shop_btn no-shop"><a href="javascript:void(0);">10元起送</a> </li>
                        <li class="shop_btn to-set" style="display: none;"><a href="javascript:void(0);" onclick="window.location.href = 'shoppingCart.aspx';">去结算</a> </li>
                    </ul>
                </div>
                <div class="foot_gwc">
                    <li class="shop_car"><a href="javascript:void(0);" id="location_url"><span><i>0</i></span></a> </li>
                    <p class="gwc_empty" style="display: none;">购物车空空~~</p>
                    <div class="gwc-cz border-b2" style="display: none;">
                        <dl class="clearfix">
                            <dt>购物车已选中<i class="goodsNum">0</i></dt>
                            <dd onclick="delGwcFun()"><em></em>清空购物车</dd>
                        </dl>
                    </div>
                    <div class="gwc-text border-b2" style="display: none;">首单满10元起送,第二单起满20元起送</div>
                    <div class="gwc_list" style="display: none;"></div>
                </div>
            </div>
            <div class="bgdiv" style="display: none;"></div>
            <!--end-->
            <!--提交表单-->
            <form id="form" method="post" action="">
                <input type="hidden" name="from" value="book">
                <input type="hidden" name="nums" value="">
                <input type="hidden" name="gids" value="">
                <input type="hidden" name="skus" value="">
                <input type="hidden" name="note" value="">
            </form>
            <!--提交表单结束-->
        </div>

js:

 <script type="text/javascript">
            $(document).ready(function () {
               
              
                //点击评价跳转
                  $("#aa1").on("click", function () {
                    var url = window.location.href;
                    var arrUrl = url.split("?");

                    var para = arrUrl[1];
                    var u = para.split("&");
                    var uu = u[0];
                    //alert(uu);
                    location.href = '/Vshop/StoreShopDetail?' + uu;
                });

               
                //点击店名跳转
                $("#sp1").on("click", function () {
                    var url = window.location.href;
                    var arrUrl = url.split("?");

                    var para = arrUrl[1];
                    var u = para.split("&");
                    var uu = u[0];
                    //alert(uu);
                    location.href = '/Vshop/StoreShopDetail?' + uu;
                });

                //左侧边栏被点击ajax加载
                $("ul#categoryli1").on("click", "li", function () {
                   
                    var u = getParam('storeId');
                    //window.location.href=para+"&categoryId="+id; 
                    // var msg = $("#txtMsg").val();
                    var id = $(this).closest("li").attr("id");
                    $.ajax({
                        type: "post", url: "/API/SotreAJAX.ashx", data: { categoryId: id, action: 'post', storeId: u },
                        success: function (data) {
                            //$("#ulMsgs").val("");
                            $('#ulMsgs').html('');
                            for (var i = 0; i < data.length; i++) {
                                var msg = data[i];

                                $("#ulMsgs").append($("<div class=\"book1ConLoop1 border-b2\"><div class=\"contfl1\"><img src=\"" + msg.ThumbnailUrl180 + "\"id=\"" + msg.ProductId + "\" onclick=\"myFunction(this)\"><div class=\"img_bg\"></div></div><div class=\"contCent1 contCent2\"><p class=\"sketch\" id=\"" + msg.ProductId + "\" onclick=\"myFunction(this)\">" + msg.ProductName + "</p><p class=\"text\">评价 " + msg.Comment + "条  |  已售 " + msg.Sale + "</p><p class=\"price\">¥<span class=\"js-unitCost\">" + msg.SalePrice + "</span> <s>/" + msg.Unit + "</s></p><p class=\"scor\">首溯评分<i>4.3</i></p></div><div class=\"contfr2 js-contfr2\"><div name=\"spAdd\" class=\"btn js-disabled\" skuid=\"" + msg.SkuId + "\" style=\"\"></div><div class=\"ChangeNum js-disabled\"  style=\"display: none;\"> <div class=\"text\"><span id=\"buyNum1\" class=\"number\">1</span></div><div class=\"plusMinus js-plusMinus\"><div name=\"spAdd\" class=\"plus\" skuid=\"" + msg.SkuId + "\"></div><div name=\"spSub\" class=\"minus\" skuid=\"" + msg.SkuId + "\"></div></div></div></div></div>"));
                            }
                        },
                        error: function () { alert("请求错误"); }
                    });



                });
               
               
                // category2下的图片高度与宽度相等 start
                function category2ImgH() {
                    //var category2ImgW = $('.category2 dd img').width();
                    //$('.category2 dd img').css('height',category2ImgW);
                }
                //category2ImgH();
                // category2下的图片高度与宽度相等 end

                $(window).resize(function () {
                    //category2ImgH();
                    fnAuto();
                    fnyScroll1H();
                });
                function fnAuto() {
                    var yScroll1W = $(".yScroll1").outerWidth();
                    var yScroll2W = $(window).width() - yScroll1W;
                    $(".yScroll2").css({/*'width':yScroll2W,'min-width':'225px'*/ }); // 获取窗口右侧内容的宽度
                }
                fnAuto();
                var typeid = $('.yScroll1 li').attr('id');
                var token = $('#token').attr('name');


                //左侧分类导航切换 start
                $(".yScroll1 li:eq(0)").addClass('cur');
                $('.yScroll2Title').text($(".yScroll1 li:eq(0)").text());
                $(".yScroll1").delegate('li', 'click', function (event) {
                    if (!$(this).hasClass('cur')) {
                        $(this).addClass('cur').siblings('li').removeClass('cur');
                        $('.yScroll2 div.index3Div').eq($(this).index()).show().siblings('div.index3Div').hide();
                        var liClickTop = $(this).index() * $(this).outerHeight();
                        $('.yScroll2').scrollTop(0);
                        $('.yScroll1').animate({ 'scrollTop': liClickTop - 1 }, 200);
                        $('.yScroll2Title').text($(this).text());
                    }
                });

              
                // 左侧分类导航切换 end

                // 判断左侧分类导航在可视区域的高度 start
                function fnyScroll1H() {
                    var spxqHeadPhoneH = $('.spxqHeadPhone').outerHeight();
                    var zunhao_headH = $('.zunhao_head').outerHeight();
                    var topGuangGaoH = $('.js-topGuangGao').outerHeight();
                    var book1FooterH = $('.js-book1Footer').outerHeight();
                    var yScroll121H = $(window).height() - spxqHeadPhoneH - zunhao_headH - topGuangGaoH - book1FooterH;
                    var yScroll122H = $(window).height() - zunhao_headH;
                    if ($(".spxqHeadPhone").css('display') == 'block') {
                        $(".wx_wrap").css({ 'height': yScroll121H });
                        $(".yScroll1").css({ 'height': yScroll121H });
                        $(".yScroll2").css({ 'height': yScroll121H });
                    } else {
                        $(".wx_wrap").css({ 'height': yScroll122H });
                        $(".yScroll1").css({ 'height': yScroll122H });
                        $(".yScroll2").css({ 'height': yScroll122H });
                    };
                }
                fnyScroll1H();
                // 判断左侧分类导航在可视区域的高度 end

                //结算
                $('.gwc_empty').hide();
                $('.gwc_list').hide();
                $('#location_url').click(function () {
                    window.location.href = 'shoppingCart.aspx';
                    //if ($('.bgdiv').is(':visible')) {
                    //    $('.bgdiv').hide();
                    //    $('.foot_gwc').animate({ 'bottom': '0' }, 200, function () {
                    //        $('.gwc_list').hide();
                    //        $('.gwc_empty').hide();
                    //        $('.gwc-cz').hide();
                    //        $('.gwc-text').hide();
                    //    });
                    //    $('.shop_car').css('margin-top', '0');
                    //} else {
                    //    $('.bgdiv').show();
                    //    $('.foot_gwc').animate({ 'bottom': '240px' }, 200);
                    //    $('.shop_car').css('margin-top', '-3.5rem');
                    //    $('.gwc-cz').show();
                    //    $('.gwc-text').show();
                    //    $('.goodsNum').text($('#location_url span i').text());

                    //    if ($(this).find('i').html() == '0') {
                    //        $('.gwc_empty').show();
                    //        $('.gwc_list').hide();
                    //    }
                    //    else {
                    //        $('.gwc_empty').hide();
                    //        $('.gwc_list').show();
                    //    }
                    //}
                })
                $('.bgdiv').click(function () {
                    $(this).hide();
                    $('.foot_gwc').animate({ 'bottom': '0' }, 200, function () {
                        $('.gwc_list').hide();
                        $('.gwc_empty').hide();
                        $('.shop_car').css('margin-top', '0');
                        $('.gwc-cz').hide();
                        $('.gwc-text').hide();

                    });
                })

                // 判断是否有被选中的商品 start
                function fnFindChecked() {
                    var checkedDisabledNum = $('.checked.js-disabled').length;
                    if ($('.js-book1Content1').find('.checked').length) {
                        $('.book1Footer .reserve').addClass('active');
                        // $('.book1Footer .reserve span i').show().text(checkedDisabledNum);
                    } else {
                        $('.book1Footer .reserve').removeClass('active');
                        $('.book1Footer .reserve span i').hide();
                    };
                }
                fnFindChecked();
                // 判断是否有被选中的商品 end

                // 点击选中商品 start
                $('.js-yScroll2').delegate('.js-contfr1 .select', 'click', function () {
                    alert("bb");
                    var gid = $(this).attr('gid');
                    var sku = $(this).attr('sku');
                    var number = 1;
                    var shop_car = parseInt($('.shop_car span i').text());
                    var price = parseFloat($(this).parent().siblings('.contCent1').children('.price').children('.js-unitCost').text());
                    var summoney = parseFloat($('.book1Footer .shop .js-num').html());
                    $(this).toggleClass('checked');
                    var info = $(this).hasClass("checked");
                    if (info) {
                        editNote(sku, gid, 1);

                        var newmoney = summoney + price;
                        $('.shop_car span i').show().html(shop_car + 1);
                        $('.book1Footer .shop .js-num').html(newmoney.toFixed(2));
                        fnFreightSum();
                    }
                    else {
                        editNote(sku, gid, -1);

                        var newmoney = summoney - price;
                        $('.shop_car span i').show().html(shop_car - 1);
                        $('.book1Footer .shop .js-num').html(newmoney.toFixed(2));
                        var ems = $('.book1Footer .shop .js-num').text();
                        if (ems == 0) {
                            $('.book1Footer .shop .js-freight').text(0);
                        }
                        fnFreightSum();
                    }

                    fnFindChecked();
                });
                // 点击选中商品 end

                // 点击显示加减商品数量 start
                $('.js-yScroll2').delegate('.js-contfr2 .btn', 'click', function () {
                    //alert("bb");
                    var gid = $(this).siblings('.ChangeNum').attr('gid');
                    var sku = $(this).siblings('.ChangeNum').attr('sku');
                    var number = $(this).siblings('.ChangeNum').children('.text').children('.number').html();
                    var shop_car = parseInt($('.shop_car span i').text());
                    var price = parseFloat($(this).parent().siblings('.contCent2').children('.price').children('.js-unitCost').text());
                    var summoney = parseFloat($('.book1Footer .shop .js-num').html());
                    var clicknum = $(this);

                    editNote(sku, gid, 1);

                    var newmoney = summoney + price;
                    $('.shop_car span i').show().html(shop_car + 1);
                    $('.book1Footer .shop .js-num').html(newmoney.toFixed(2));
                    clicknum.hide().siblings('.ChangeNum').show().addClass('checked');
                    fnFreightSum();
                    fnFindChecked();
                    $('.shop_car').addClass('active');
                    $('.shop .no-shop').hide();
                    $('.shop .has-price').show();
                    $('.shop_btn.no-shop').hide();
                    $('.shop_btn.to-set').show();

                });
                // 点击显示加减商品数量 end

                //编辑note记录商品信息
                function editNote(sku, gid, number) {
                    var oldNote = $('input[name=note]').val();
                    if (oldNote == '') {
                        $('input[name=note]').val('[{sku:"' + sku + '",gid:' + gid + ',number:' + number + '}]');
                    }
                    else {
                        var obj = eval("(" + oldNote + ")");
                        //搜索是否有这个sku
                        var flag = 0;
                        for (var arr in obj) {
                            if (obj[arr]['sku'] == sku) {
                                obj[arr]['number'] = parseInt(number) + parseInt(obj[arr]['number']);
                                if (obj[arr]['number'] <= 0) {
                                    obj.splice(arr, 1);
                                }
                                flag = 1;
                            }
                        }
                        if (flag == 1) {
                            var str = JSON.stringify(obj);
                            $('input[name=note]').val(str);
                        }
                        else {
                            obj.push({ sku: sku, gid: gid, number: number });
                            var str = JSON.stringify(obj);
                            $('input[name=note]').val(str);
                        }
                    }
                }

                // 增加商品数量 start
                $('.js-yScroll2').delegate('.plus', 'click', function () {
                    var textNum = parseInt($(this).parent().siblings('.text').children('span').text());
                    //$(this).parent().siblings('.text').children('span').text(textNum + 1);
                    var thisnum = $(this);
                    var gid = $(this).parents('.ChangeNum').attr('gid');
                    var sku = $(this).parents('.ChangeNum').attr('sku');
                    var number = $(this).parent().siblings('.text').children('span').html();
                    var price = parseFloat($(this).parents().siblings('.contCent2').children('.price').children('.js-unitCost').text());
                    //var shop_car = parseInt($('.shop_car span i').text());
                    var summoney = parseFloat($('.book1Footer .shop .js-num').text());

                    editNote(sku, gid, 1);

                    thisnum.parent().siblings('.text').children('span').text(textNum + 1);
                    var number1 = thisnum.parent().siblings('.text').children('span').html();
                    var newmoney = summoney + price;
                    $('.book1Footer .shop .js-num').html(newmoney.toFixed(2));
                    fnFreightSum();
                });
                // 增加商品数量 end

                // 减少商品数量 start
                $('.js-yScroll2').delegate('.minus', 'click', function () {
                    var textNum = parseInt($(this).parent().siblings('.text').children('span').text());
                    $(this).parent().siblings('.text').children('span').text(textNum - 1);
                    var gid = $(this).parents('.ChangeNum').attr('gid');
                    var sku = $(this).parents('.ChangeNum').attr('sku');
                    var number = $(this).parent().siblings('.text').children('span').html();
                    var shop_car = parseInt($('.shop_car span i').text());
                    var price = parseFloat($(this).parents().siblings('.contCent2').children('.price').children('.js-unitCost').text());
                    var summoney = parseFloat($('.book1Footer .shop .js-num').text());

                    editNote(sku, gid, -1);

                    var newmoney = summoney - price;
                    $('.book1Footer .shop .js-num').html(newmoney.toFixed(2));
                    var ems = $('.book1Footer .shop .js-num').text();
                    if (ems == 0) {
                        $('.book1Footer .shop .js-freight').text(0);
                    }
                    fnFreightSum();
                    if (textNum - 1 <= 0) {
                        $('.shop_car span i').show().html(shop_car - 1);
                        $(this).parent().parent('.ChangeNum').hide().removeClass('checked').siblings('.btn').show();
                        $(this).parent().siblings('.text').children('span').text(1);
                        fnFindChecked();
                    };
                    if ($('.has-price .js-num').text() == '0.00') {
                        $('.shop_car').removeClass('active');
                        $('.shop .no-shop').show();
                        $('.shop .has-price').hide();
                        $('.shop_btn.no-shop').show();
                        $('.shop_btn.to-set').hide();

                    }
                });
                // 减少商品数量 end

                //初始化商品信息
                function initGoods() {
                    var initGoods = [];
                    if (initGoods != '') {
                        var str = JSON.stringify(initGoods);
                        $('input[name=note]').val(str);
                    }
                }
                initGoods();

                // 每选一次商品 都会重新获取一次被选中的预定商品总数 start
                $('.js-book1Content1').delegate('.js-disabled', 'click', function () {
                   // alert("sel");
                    var checkedDisabledNum = $('.checked.js-disabled').length;
                    if (!checkedDisabledNum) {
                        $('.book1Footer .reserve span i').hide();
                    } else {
                        //$('.book1Footer .reserve span i').show().text(checkedDisabledNum);
                    };
                    fnFreightSum();
                });

                // 判断运费金额 start
                function fnFreightSum() {
                    var jsNumText = $('.book1Footer .shop .js-num').text();
                    //alert(jsNumText);
                    if (jsNumText < 10 && jsNumText != 0 && jsNumText != 0.01) {
                        $('.book1Footer .shop .js-freight').text(3);
                    } else {
                        $('.book1Footer .shop .js-freight').text(0);
                    };
                }
                fnFreightSum();
                var num = 0;
                $('.btn.js-disabled').bind('click', function () {
                    num++;
                    var book1ConLoop1 = $(this).parents('.book1ConLoop1');
                    book1ConLoop1.attr('id', 'goods' + num);
                    var sketch = book1ConLoop1.find('.sketch');
                    var jsUnitCost = book1ConLoop1.find('.js-unitCost');
                    var goodsId = book1ConLoop1.attr('id');
                    $('.gwc_list').append('<div class="g_li" id="' + goodsId + '"><div class="g_title"><span class="l_t">' + sketch.html() + '</span><span class="pl5" style="display:none;">¥</span><span class="l_p" style="display:none;">' + jsUnitCost.html() + '</span></div><div class="g_btn"> <span class="minus"></span>  <span class="number">1</span><span class="plus"></span></div></div>');
                    var g_l = $('.gwc_list .g_li').length;
                    for (var i = 0; i < g_l - 1; i++) {
                        $('.gwc_list .g_li').eq(i).css('border-bottom', '1px #dcdcdc solid');
                    }
                })
                $('.plusMinus.js-plusMinus .plus').bind('click', function () {
                    var book1ConLoop1 = $(this).parents('.book1ConLoop1');
                    var goodsId = book1ConLoop1.attr('id');
                    var text = book1ConLoop1.find('.text');
                    $('.no-shop').hide();
                    $('.has-price').show();
                    $('.shop_car').addClass('active');
                    $('.shop_btn.no-shop').hide();
                    $('.shop_btn.to-set').show();
                    $('.gwc_list .g_li').each(function () {
                        if ($(this).attr('id') == goodsId) {
                            var thisNum = parseInt($(this).find('.number').html());
                            thisNum++;
                            $(this).find('.number').html(thisNum);
                        }

                        if ($(this).is(':last')) {
                            $(this).css('border-bottom', 'none')
                        }
                    })
                })

                $('.plusMinus.js-plusMinus .minus').bind('click', function () {
                    var book1ConLoop1 = $(this).parents('.book1ConLoop1');
                    var goodsId = book1ConLoop1.attr('id');
                    var text = book1ConLoop1.find('.text');
                    $('.gwc_list .g_li').each(function () {
                        if ($(this).attr('id') == goodsId) {
                            var thisNum = parseInt($(this).find('.number').html());
                            thisNum--;
                            if (thisNum == 0) {
                                $(this).remove();
                            } else {
                                $(this).find('.number').html(thisNum);
                            }
                        }
                    })
                })

                $(document).on('click', '.g_btn .plus', function () {
                    var gNum = parseInt($(this).siblings('.number').text());
                    gNum++;
                    $(this).siblings('.number').text(gNum);
                    var dPrice = parseFloat($(this).parents('.g_li').find('.l_p').text())
                    var sNum = parseFloat($('.shop .js-num').text());
                    $('.shop .js-num').text((sNum + dPrice).toFixed(2));
                    if (sNum + dPrice >= 15) {
                        $('.js-freight').text(0);
                    }

                    var gId = $(this).parents('.g_li').attr('id');
                    $('.book1ConLoop1').each(function () {
                        if ($(this).attr('id') == gId) {
                            var t_num = parseInt($(this).find('.number').text());
                            t_num++;
                            $(this).find('.number').text(t_num);

                        }

                    })

                })


                $(document).on('click', '.g_btn .minus', function () {
                    var gNum = parseInt($(this).siblings('.number').text());
                    gNum--;
                    if (gNum == 0) {
                        $(this).parents('.g_li').remove();
                        var l_length = parseInt($('#location_url span i').text());
                        l_length--;
                        if (l_length == 0) {

                            $('.gwc_empty').show();
                            $('.shop .js-freight').html('0');
                        }
                        $('#location_url span i').text(l_length);

                    }
                    else {

                        $(this).siblings('.number').text(gNum);
                    }




                    var dPrice = parseFloat($(this).parents('.g_li').find('.l_p').text())
                    var sNum = parseFloat($('.shop .js-num').text());
                    $('.shop .js-num').text((sNum - dPrice).toFixed(2));
                    if (sNum - dPrice < 15) {
                        $('.js-freight').text(3);
                    }
                    if ($('#location_url').text() == 0) {
                        $('.js-freight').text(0);

                    }
                    var gId = $(this).parents('.g_li').attr('id');
                    $('.book1ConLoop1').each(function () {
                        if ($(this).attr('id') == gId) {
                            var t_num = parseInt($(this).find('.number').text());
                            t_num--;

                            if (t_num == 0) {
                                $(this).find('.ChangeNum.js-disabled.checked').hide();
                                $(this).find('.btn.js-disabled').show();
                                $(this).find('.number').text(1);
                            }
                            else {
                                $(this).find('.number').text(t_num);
                            }
                        }

                    })

                    if ($('.has-price .js-num').text() == '0.00') {
                        $('.shop_car').removeClass('active');
                        $('.shop .no-shop').show();
                        $('.shop .has-price').hide();
                        $('.shop_btn.no-shop').show();
                        $('.shop_btn.to-set').hide();
                        $('.shop_car').css('margin-top', '0');
                        $('.foot_gwc').animate({ 'bottom': '0' }, 200, function () {
                            $('.gwc_list').hide();
                            $('.gwc_empty').hide();
                        });
                        $('.bgdiv').hide();
                        $('.gwc-cz').hide();
                        $('.gwc-text').hide();
                    }

                    $('.goodsNum').text($('#location_url span i').text());

                })

            });

            function myFunction(obj) {
                window.location.href = "/Wapshop/ProductDetails?ProductId=" + obj.id;
            }
            function delGwcFun() {
                $('.shop_car').removeClass('active');
                $('.shop .no-shop').show();
                $('.shop .has-price').hide();
                $('.shop .has-price.js-num').text('0.00');
                $('.gwc_list').html('');
                $('.contfr2 .ChangeNum').hide().removeClass('.checked');
                $('.ChangeNum .number').text(1);
                $('.has-price .js-num').text(0);
                $('.contfr2 .btn').show();
                $('.shop_btn.no-shop').show();
                $('.shop_btn.to-set').hide();
                $('#location_url span i').text(0);
                $('.goodsNum').text(0);
                $('.shop_car').css('margin-top', '0');
                $('.foot_gwc').animate({ 'bottom': '0' }, 200, function () {
                    $('.gwc_list').hide();
                    $('.gwc_empty').hide();
                });
                $('.bgdiv').hide();
                $('.gwc-cz').hide();
                $('.gwc-text').hide();
            }

            //------------------------页面加载ajax请求-----------------从这开始---------------------------
            $(function () {
                var url = window.location.href;
               
                var u = getParam('storeId');
                
                $.ajax({
                    type: "post", url: "/API/SotreAJAX.ashx", data: { action: 'loadMsgs', storeId: u },
                    success: function (data) {
                        for (var i = 0; i < data.length; i++) {
                            var msg = data[i];
                            $("#ulMsgs").append($("<div class=\"book1ConLoop1 border-b2\"><div class=\"contfl1\"><img src=\"" + msg.ThumbnailUrl180 + "\"id=\"" + msg.ProductId + "\" onclick=\"myFunction(this)\"><div class=\"img_bg\"></div></div><div class=\"contCent1 contCent2\"><p class=\"sketch\" id=\"" + msg.ProductId + "\" onclick=\"myFunction(this)\">" + msg.ProductName + "</p><p class=\"text\">评价 " + msg.Comment + "条  |  已售 " + msg.Sale + "</p><p class=\"price\">¥<span class=\"js-unitCost\">" + msg.SalePrice + "</span> <s>/" + msg.Unit + "</s></p><p class=\"scor\">首溯评分<i>4.3</i></p></div><div class=\"contfr2 js-contfr2\"><div name=\"spAdd\" class=\"btn js-disabled\" skuid=\"" + msg.SkuId + "\" style=\"\"></div><div class=\"ChangeNum js-disabled\"  style=\"display: none;\"> <div class=\"text\"><span id=\"buyNum1\" class=\"number\">1</span></div><div class=\"plusMinus js-plusMinus\"><div name=\"spAdd\" class=\"plus\" skuid=\"" + msg.SkuId + "\"></div><div name=\"spSub\" class=\"minus\" skuid=\"" + msg.SkuId + "\"></div></div></div></div></div>"));
                        }
                    },
                    error: function () { alert("请求错误"); }
                });
            });

            //点击+加入购物车ajax请求这个+只有点击的时候发出一次之后被隐藏了
            $('.js-yScroll2').delegate('.js-contfr2 .btn', 'click', function () {

                var number = $("#buyNum").html();

                // alert(number);
                var skuId = $(this).attr("skuid");
                //alert(skuId);
                $.ajax({
                    url: "/API/VshopProcess.ashx",
                    type: 'post', dataType: 'json', timeout: 10000,
                    data: { action: "AddToCartBySkus", quantity: 1, productSkuId: skuId },
                    async: false,
                    success: function (resultData) {
                        if (resultData.Status == "OK") {
                            var xtarget = $("#addcartButton").offset().left;
                            var ytarget = $("#addcartButton").offset().top;
                            UpdateSpCount(skuId, resultData.SkuQuantity);
                            $("#divshow").css("top", "200px");
                            $("#divshow").css("left", parseInt(xtarget) + "px");

                            ShowMsg("商品已经添加至购物车", true);
                            $(".att-popup").removeClass('is-visible');
                            //myConfirmBox('添加成功', '商品已经添加至购物车', '现在去购物车', '再逛逛', function () { location.replace('ShoppingCart.aspx'); }, function () { location.replace("default.aspx"); });
                            //显示添加购物成功
                        }
                        else {
                            // 商品已经下架
                            ShowMsg("此商品已经不存在(可能被删除或被下架)", false);
                            return false;
                        }
                    }
                });
                //chageCartProductQuantity(number, skuId);
                //购物车 + 数量
                // $('div[name="spAdd"]').bind("click", function () {
                $('.js-yScroll2').delegate('.plus', 'click', function () {
                    var number = $("#buyNum").html();

                    var number = parseInt(number);
                    // alert(number);

                    var skuId = $(this).attr("skuid");
                    // alert(skuId);
                    //chageCartProductQuantity(number, skuId);
                    $.ajax({
                        url: "/API/VshopProcess.ashx",
                        type: 'post', dataType: 'json', timeout: 10000,
                        data: { action: "AddToCartBySkus", quantity: 1, productSkuId: skuId },
                        async: false,
                        success: function (resultData) {
                            if (resultData.Status == "OK") {
                                var xtarget = $("#addcartButton").offset().left;
                                var ytarget = $("#addcartButton").offset().top;
                                UpdateSpCount(skuId, resultData.SkuQuantity);
                                $("#divshow").css("top", "200px");
                                $("#divshow").css("left", parseInt(xtarget) + "px");

                                ShowMsg("商品已经添加至购物车", true);
                                $(".att-popup").removeClass('is-visible');
                                //myConfirmBox('添加成功', '商品已经添加至购物车', '现在去购物车', '再逛逛', function () { location.replace('ShoppingCart.aspx'); }, function () { location.replace("default.aspx"); });
                                //显示添加购物成功
                            }
                            else {
                                // 商品已经下架
                                ShowMsg("此商品已经不存在(可能被删除或被下架)", false);
                                return false;
                            }
                        }
                    });
                });
                //购物车 - 数量
                //$('div[name="spSub"]').bind("click", function () {
                $('.js-yScroll2').delegate('.minus', 'click', function () {
                    var number = parseInt($(this).parent().siblings('.text').children('span').text());

                    var number = parseInt(number);
                    // alert(number);

                    var skuId = $(this).attr("skuid");
                    if (number > 0)
                        
                        chageCartProductQuantity(number, skuId);
                });
            });

            // /vshop/shoppingCart 修改购物车商品数量,obj:最新数量   skuId:商品SkuId
            function chageCartProductQuantity(obj, skuId) {
                $.ajax({
                    url: "/API/VshopProcess.ashx",
                    type: 'post',
                    dataType: 'json',
                    timeout: 10000,
                    data: {
                        action: "ChageQuantity",
                        //skuId: $(obj).attr("skuId"),
                        //quantity: parseInt($(obj).val())
                        skuId: skuId,
                        quantity: obj
                    },
                    success: function (resultData) {
                        if (resultData.Status != "OK") {
                            alert("最多只可购买" + resultData.Status + "件");
                        } else {
                            $("i[gid=giftNum_" + skuId).text(parseInt($(obj).val()));
                            $("#spanPrice" + skuId).html(resultData.adjustedPrice);
                            $('#totalPrice').html('¥' + parseFloat(resultData.TotalPrice).toFixed(2));
                        }
                    }
                });
            }

            function BuyProductToCart() {

                $.ajax({
                    url: "/API/VshopProcess.ashx",
                    type: 'post', dataType: 'json', timeout: 10000,
                    data: { action: "AddToCartBySkus", quantity: parseInt($("#buyNum").val()), productSkuId: $("#hiddenSkuId").val() },
                    async: false,
                    success: function (resultData) {
                        if (resultData.Status == "OK") {
                            var xtarget = $("#addcartButton").offset().left;
                            var ytarget = $("#addcartButton").offset().top;
                            UpdateSpCount($("#hiddenSkuId").val(), resultData.SkuQuantity);
                            $("#divshow").css("top", "200px");
                            $("#divshow").css("left", parseInt(xtarget) + "px");
                            myConfirmBox('添加成功', '商品已经添加至购物车', '现在去购物车', '再逛逛', function () { location.replace('ShoppingCart.aspx'); }, function () { location.replace("default.aspx"); });
                            //显示添加购物成功
                        }
                        else {
                            // 商品已经下架
                            alert_h("此商品已经不存在(可能被删除或被下架),暂时不能购买" + resultData.Status);
                        }
                    }
                });
            }
        </script>
    </section>
</body>
</html>

/API/SotreAJAX.ashx:

获取的字段来自5张表,首先尝试了用属性点,发现有的属性为空,然后尝试用DTO做,查询内容包括:商品名称、每个商品评论、已售、单价、图片路径、单位、skuid、productid。

ProductDTO:

 public  class ProductDTO
    {
        public string ProductName { set; get; }

        public int ProductId { set; get; }

        public decimal SalePrice { set; get; }
public string SkuId { set; get; } public string ThumbnailUrl180 { set; get; } public string Unit { set; get; } public int Comment { set; get; } public int Sale { set; get; } }
ProductDal:
 public  class ProductDal
    {
        private string ConnectionString;

        public ProductDal()
        {
            this.ConnectionString = ConfigurationManager.ConnectionStrings["HidistroSqlServer"].ConnectionString;
        }

        private ProductDTO ToProductDTO(DataRow row)
        {
            ProductDTO product = new ProductDTO();
            product.ProductName = row["ProductName"].ToNullString();
            product.ProductId = row["ProductId"].ToInt();
            product.SalePrice = row["SalePrice"].ToDecimal();
            product.SkuId = row["SkuId"].ToNullString();
            product.ThumbnailUrl180 = row["ThumbnailUrl180"].ToNullString();
            product.Unit = row["Unit"].ToNullString();
            product.Comment = row["Comment"].ToInt();
            product.Sale = row["Sale"].ToInt();

            return product;
        }
        public IEnumerable<ProductDTO> GetAll(int storeId,int categoryId)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(@"SELECT  p.Unit ,
        p.ThumbnailUrl180 ,
        pp.Comment ,
        p.ProductName ,
        p.ProductId ,
        s.SkuId ,
        s.SalePrice ,
        poi.Sale
FROM    Hishop_Products AS p
        LEFT JOIN ( SELECT  ps.ProductID AS ProductID ,
                            COUNT(ps.ProductId) AS Comment
                    FROM    Hishop_ProductReviews AS ps
                            JOIN Hishop_Products AS p ON p.ProductID = ps.ProductID
                    GROUP BY ps.ProductID
                  ) pp ON p.ProductID = pp.ProductID
        LEFT JOIN ( SELECT  pht.ProductID ,
                            COUNT(pht.ProductID) AS Sale
                    FROM    Hishop_Products AS p
                            JOIN Hishop_OrderItems AS pht ON p.ProductID = pht.ProductID
                    GROUP BY pht.ProductID
                  ) poi ON poi.ProductID = p.ProductID
        LEFT JOIN Hishop_Categories AS c ON p.CategoryId = c.CategoryId
        LEFT JOIN Hishop_SKUs AS s ON p.ProductId = s.ProductId
WHERE   p.StoreId =@StoreId ");
            if (categoryId>= 0)
            {
                sb.AppendLine("AND  p.CategoryId=@CategoryId");
            }
            
            DataTable dt = SqlHelper.ExecuteQuery(sb.ToString(), new SqlParameter("@StoreId", storeId), new SqlParameter("@CategoryId", categoryId));
            List<ProductDTO> list = new List<ProductDTO>();
            foreach (DataRow row in dt.Rows)
            {
                ProductDTO log = ToProductDTO(row);
                list.Add(log);//list.Add(ToLog(row));
            }
            return list;
        }

       
    }

SotreAJAX:

 public class SotreAJAX : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            string action = context.Request["action"];
            List<ProductDTO> p;
            string id = context.Request["storeId"];
         
            //页面加载
            if (action == "loadMsgs")
            {
                p = ProductHelper.GetAll(int.Parse(id), -1).ToList();
               
                context.Response.Write(new JavaScriptSerializer().Serialize(p));
            }
            //点击加载
            else if (action == "post")
            {
                string ids = context.Request["categoryId"];
                p = ProductHelper.GetAll(int.Parse(id), int.Parse(ids)).ToList();
             
                context.Response.Write(new JavaScriptSerializer().Serialize(p));
            }
            else
            {
                throw new Exception("action错误");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

/API/VshopProcess.ashx/AddToCartBySkus:商品详情页加入购物车

 private void ProcessAddToCartBySkus(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            int quantity = int.Parse(context.Request["quantity"], 0);
            string productSkuId = context.Request["productSkuId"];
            var productId = context.Request["productSkuId"].ToNullString().Split('_')[0].ToInt();
            if (quantity <= 0) quantity = 1;
            Hidistro.SaleSystem.Shopping.ShoppingCartProcessor.AddLineItem(productSkuId, quantity);
            ShoppingCartInfo shoppingCart = Hidistro.SaleSystem.Shopping.ShoppingCartProcessor.GetShoppingCart();
            if (shoppingCart != null)
                context.Response.Write("{\"Status\":\"OK\",\"TotalMoney\":\"" + shoppingCart.GetTotal().ToString(".00") + "\",\"Quantity\":\"" + shoppingCart.GetQuantity().ToString() + "\",\"SkuQuantity\":\"" + shoppingCart.GetQuantity_Sku(productSkuId) + "\"}");
            else
                context.Response.Write("{\"Status\":\"0\"}");
        }

猜你喜欢

转载自www.cnblogs.com/symkmk123/p/9092514.html