加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

利用getJson+ashx实现商品属性选择(C#)

发布时间:2020-12-16 19:17:08 所属栏目:百科 来源:网络整理
导读:1、前台页面(注意引入jQuery框架): %@ Page Language="C#" AutoEventWireup="true" CodeFile="shopDetail.aspx.cs" Inherits="shopDetail" %!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-tra

1、前台页面(注意引入jQuery框架):

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="shopDetail.aspx.cs" Inherits="shopDetail" %>

<!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 runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<meta charset="utf-8"> 
<title>宝贝详情</title> 
<meta content="yes" name="apple-mobile-web-app-capable">
 <meta content="black" name="apple-mobile-web-app-status-bar-style"> 
 <meta name="format-detection" content="telephone=no"> 
 <style>
    .liselect a
    {
        border: 2px solid #DF0001;
        box-shadow: 1px 1px 3px 0 rgba(0,0.6);
        margin: -1px;
    }
</style>
  <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
  <link rel="stylesheet" type="text/css" href="css/index-black.css" />
  <style type="text/css">
img {width:expression(this.width>300?"300px":this.width+"px");}
</style>

<%--注意引入JQuery框架--%>
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
 

<!--//商品属性选择器开始-->
<script type="text/javascript">
var imgmultbf="";//多图备份
$(document).ready(function(){

$(".product_size").mouSEOut(function(){ $(this).removeAttr("style"); })
$(".product_size").mouSEOver(function(){$(".product_size").attr("style","border:1px solid #fcbb29;background:#FFF3D9;")});

$(".restrict ul li").not(".litit").each(function(i){ $(this).click(function()
{ 
    
   $(this).siblings().not(".litit").children("img").remove();
   $(this).siblings().not(".litit").removeAttr("class");
   $(this).attr("class","liselect");
   $(this).append($("<img class="sico" src="Images/ii1.gif" />"));
   $("#divnoSelect").hide();
   $("#divSelect").show();
   var spenames="";
   var isselect=0; //规格选择的个数
   var prodspec="";//选择的规格值(所有已勾选的规格值)
   var nowprodspec="";//当前选择的规格值
   var prodguid=$("#HiddenFieldGuid").val();  //商品guid
   var memloginid=$("#HiddenFieldMemloginID").val();//会员loginid
   if(imgmultbf=="")
   {
    imgmultbf=$("#tb_gallery").html();//多图备份
    }
   //开始处理多图(使用getJson+ashx实现数据交互,但ajaxPro2与getJson不能同时使用)
     nowprodspec=$(this).attr("spc");
     params = {"prodguid":prodguid,"yz":"shopnum1ntbl","loginid":memloginid,"spec":nowprodspec,"type":"img"}; 
      $.getJSON("/Api/shopproductspec.ashx",params,function(json){
     
             if(json[0].imgsrc!=null)
             {
           //绑定选择规格后的大图
            $("#ProductDetail_ctl00_RepeaterData_ctl00_ProductImgurl").attr("src",""+json[0].imgsrc+"");
            $("#ProductDetail_ctl00_RepeaterData_ctl00_ProductImgurl").attr("jqimg",""+json[0].imgsrc.replace("s_","")+"");
            //绑定属性的缩略图
            $(".list-h li").remove();
            
            
$.each(json,function(i) {
 if(json[i].imgsrc!="")
    {
    $(".list-h").append($("<li class="tb_diply"></li>").append($("<div class="tb-pic tb-stn"></div>").append($("<a></a>").append($("<img />").attr("src",json[i].imgsrc)))))
    }
});
    //给缩略图加宽度
           var width_l=parseInt(json.length)*60;
//           $(".list-h").attr("style","");		
//				  $(".list-h").css({
//						"width":""+width_l+"px"
//					});
             }
             else
             {
  
              $("#tb_gallery").html(imgmultbf);

             }
				$("#tb_gallery img").bind("mouSEOver",function(){
					var src=$(this).attr("src");
					$("#spec-n1 img").eq(0).attr({
						src:src.replace("/n5/","/n1/"),jqimg:src.replace("/n5/","/n0/")
					});
					$(this).parent().parent().parent().addClass("tb_selected");
				}).bind("mouSEOut",function(){
		            $(this).parent().parent().parent().removeClass("tb_selected");
				});	
             });
   //处理多图结束
   //开始处理其它效果
   var juls=$(".restrict ul")  
    juls.each(function(i){
if($(this).children("li").hasClass("liselect"))
        {
           isselect++;
           spenames+="""+$(this).children(".liselect").find("span").html()+"""+"  ";
           prodspec=prodspec+$(this).children(".liselect").attr("spc")+";";
           
           // 添加的
           document.getElementById('<%=HiddenFieldGuiGe.ClientID %>').value=prodspec;
           
         }
  
     });
     $("#divSelect .selected").html(spenames);  //选择了  
     
     
     
    //开始处理商品库存
    if(juls.length==isselect)
    {
        //使用getJson+ashx
        prodspec=prodspec.substring(0,prodspec.length-1);
        params = {"prodguid":prodguid,"spec":prodspec,"type":"prodspec"}; 
        $.getJSON("api/productspec.ashx",function(json){
        //alert('aa');
             if(json!=null)
             {
                $("#LabelShopPrice").text(json[0].price);//商品价格(jQuery格式)
                $("#LabelRepertoryCount").text(json[0].RepertoryCount);//库存(jQuery格式)
                  
             } });
       }
    
     }
     
    
     
     });})});

function  checkSubmit()  //检查数量
{
 ///检查库存
 var buyNum=document.getElementById("<%=TextBoxBuyNum.ClientID %>").value;
 var numyz=/^[0-9]{1,9}$/;
if(!numyz.exec(buyNum))
{
   alert("购买数量格式不正确!")
   document.getElementById("<%=TextBoxBuyNum.ClientID %>").get(0).focus();
   return false;
}

 var allcout=$("#LabelRepertoryCount").text();
 if(parseInt(buyNum)>=parseInt(allcout))
 {
   alert("库存不足!")
   return false;
 }
 
 //检查规格
// var juls=$(".restrict ul")  
var juls=$(".restrict ul")  
 var spenames="";
    juls.each(function(i){
     if($(this).children(".liselect").length==0)
     {

       spenames+="""+$.trim($(this).children(":first-child").find("span").text())+"""+" ";
     }
  
     });
 if(spenames!="")
 {
   alert("请选择  "+spenames);
   return false;
 }
 
}

</script>


<!--购买数量加减-->

<script type="text/javascript">

//加
function AddNum()
{
   var BuyNum=parseInt(document.getElementById("<%=TextBoxBuyNum.ClientID %>").value);
   document.getElementById("<%=TextBoxBuyNum.ClientID %>").value=BuyNum+1;
}

function SubNum()
{
   var BuyNum=parseInt(document.getElementById("<%=TextBoxBuyNum.ClientID %>").value);
   if(BuyNum>1)
   {
   document.getElementById("<%=TextBoxBuyNum.ClientID %>").value=BuyNum-1;
   }
}
</script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
     <div class="viewport enableNavbar enableToolbar enableTransition"> 
 <header class="navbar">
 <ul><li>商品详情</li><li>
 <a class="c-btn c-btn-aw" data-id="btn-1387959379238" href="javascript:history.go(-1);"><span>返回</span></a></li>
 <li></li></ul>
 </header>
  <section class="content" style="min-height: 451px;">
  <div class="wrap"><div class="inactive prev" index="0">
  </div>
  <div class="active" index="1" data-fragment="" style="min-height: 451px;">
  <div id="J_detail" style="min-height: 451px;">
  <div id="J_detail_main">
  <div class="dt-slider">
  <div class="dt-slider-cont" style="width: 354px; -webkit-transform: translateZ(0px);"> 
  <ul class="dt-slct-ul" style="-webkit-transform: translate3d(0px,0px,0px); -webkit-backface-visibility: hidden; width: 1416px;"> 
  
   <li style="width:354px" l="1"> 
	<img class="" src="http://localhost:8011<%=pPic%>"> 
	</li> 
	 </ul> 
	 <div class="dt-slider-mask"></div> </div> 
	 <%--<div class="dt-slider-status">  
	 <i class="sel"></i>  <i></i>  <i></i>  <i></i> 
	  </div>--%>
	   <ul class="dts-ul">  <li class="dts-fav"><a href="?type=fav&guid=<%=Guid %>">收藏</a></li> 
	   <li class="dts-faved">已收藏</li> 
	    </ul> </div>
	    <div class="dt-info"><h1 class="dtif-h"><%=pName%></h1> 

	    <ul>  <li class="dtif-p1"> 
	     <ins class="orange">¥<%--<%=sPrice %>--%>
	     <asp:Label ID="LabelShopPrice" runat="server"></asp:Label>
	     </ins><br> <span class="lgray dtif-ps1"><del>¥<%=mPrice %></del></span>   </li>  
	      <li class="dtif-p2 bt lgray"> 
	      <span class="dtifp-l">  库存: 
	      <asp:Label ID="LabelRepertoryCount" CssClass="storage" runat="server"></asp:Label>
                                        <asp:Label ID="Label2" runat="server"></asp:Label> </span> 
	      <%--<span  width=35px>已售<%=saleNum %>笔</span> --%>
	      <span class="dtifp-r">数量:</span>
	      <span  width=100px><span class="decrease" onclick="SubNum();"></span><asp:TextBox ID="TextBoxBuyNum" CssClass="amount_widget" runat="server" Text="1" />
           <span class="increase" onclick="AddNum();"></span>
           <%--<asp:Label ID="LabelUnit" runat="server" Text='<%# ((DataRowView)Container.DataItem).Row["UnitName"] %>'></asp:Label>--%></span> 
	        </li>
	     <li class="dtif-p2 bt lgray"> 
	      <span class="dtifp-l">  <%=GetFeeByProGuid()%>  </span> 
	      <span  width=35px>已售<%=saleNum %>笔</span> 
	      <span class="dtifp-r"><%=address %></span>  </li>  </ul> 
	      
	     </div>

	 <!--商品规格 20140415-->
	 <asp:HiddenField ID="HiddenFieldGuiGe" runat="server" Value="0"></asp:HiddenField>
	  <div class="restrict" id="divShopSpec" runat="server" visible="false" >
           <asp:Repeater ID="RepeaterProductSepc" runat="server" EnableViewState="false" OnItemDataBound="RepeaterProductSepc_ItemDataBound">
                                                <ItemTemplate>
                                                    <dl class="tb_prop clearfix">
                                                        <dt>
                                                            <%#((System.Data.DataRowView)Container.DataItem).Row["SpecificationName"]%>:</dt>
                                                        <dd>
                                                            <ul>
                                                                <asp:Repeater ID="RepeaterProductSepcDetail" runat="server" EnableViewState="false">
                                                                    <ItemTemplate>
                                                                        <li spc='<%#((System.Data.DataRowView)Container.DataItem).Row["SpecDetail"]%>'><a href="javascript:void(0)">
                                                                       <%-- <a href="javascript:View()">--%>
                                                                            <span>
                                                                                <%#((System.Data.DataRowView)Container.DataItem).Row["isImage"].ToString() == "True" ? "<img src='/ImgUpload/" + ((System.Data.DataRowView)Container.DataItem).Row["Image"] + "' width="40" height="16" />" : ((System.Data.DataRowView)Container.DataItem).Row["Name"]%></span></a></li>
                                                                    </ItemTemplate>
                                                                </asp:Repeater>
                                                            </ul>
                                                        </dd>
                                                    </dl>
                                                </ItemTemplate>
                                                <FooterTemplate>
                                                    <div id="divnoSelect" style="clear: both; padding-top: 6px; padding-top: 0px9;">
                                                        <span style="font-weight: bold; clear: both;">请选择</span>:<span id="spanNoSelect"
                                                            style="font-weight: bold; clear: both;" runat="server"><asp:Label ID="lblSpecName" runat="server" ></asp:Label> </span>
                                                    </div>
                                                    <div id="divSelect" style="clear: both; display: none;">
                                                        <span style="font-weight: bold; clear: both;">已选择</span>:<span class="selected"></span></div>
                                                    </div>
                                                </FooterTemplate>
                                            </asp:Repeater>
                                        </div>
               <div class="dt-action"> <div class="dta-iner">  
            
 </div></div>

 </div>
 </div></div></div><div class="inactive next" index="2"></div><div class="inactive" index="3"></div><div class="inactive" index="4"></div>
     </div><div class="trans"><div></div></div></section>  </div> 
     

<asp:HiddenField ID="HiddenFieldGuid" runat="server" Value="0" />
<asp:HiddenField ID="HiddenFieldMemloginID" runat="server" Value="0" />
    </form>
</body>
</html>

2、后台页面由自己项目决定,省略

3、ashx页面:

<%@ WebHandler Language="C#" Class="productspec" %>

using System;
using System.Web;
using System.Data;
using System.Text;
using mshopClass;

public class productspec : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string prodguid = context.Request["prodguid"].ToString();
        string memloginid = context.Request["loginid"].ToString();
        string spec = context.Request["spec"].ToString();
        string spectype = context.Request["type"].ToString();
        string sql = "select price,repertorycount from tb1_SpecificationProudct where productGuid='" + prodguid + "' and detail='" + spec + "'";
        DataTable dt = mallCtr.SqlTable(sql);
        StringBuilder tb = new StringBuilder();
        tb.Append(DataTableToJSON(dt));  //DataTabel一定要转化长json格式才能正常返回
        context.Response.Write(tb.ToString());
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

    /// <summary>
    /// 将dt转化成Json数据 格式如 table[{id:1,title:'体育'},id:2,title:'娱乐'}]
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static string DataTableToJSON(DataTable dt)
    {
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.Append("[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (i > 0)
                jsonBuilder.Append(",");
            jsonBuilder.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                if (j > 0)
                    jsonBuilder.Append(",");
                jsonBuilder.Append(dt.Columns[j].ColumnName.ToLower() + ": '" + dt.Rows[i][j].ToString().Replace("t"," ").Replace("r"," ").Replace("n"," ").Replace("'","'") + "'");
            }
            jsonBuilder.Append("}");
        }
        jsonBuilder.Append("]");
        return jsonBuilder.ToString();
    }
    

}

4、效果:

(1)商品属性未选择前:


(2)商品属性选择后:



5、实例下载:利用getJson+ashx实现商品属性选择实例下载

PS:AjaxPro2和getJson+ashx都能实现前后台数据交互,各有优劣,看个人喜好选择。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读