ASP.NET 使用AJAX

ajaxHandler.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ajaxHandler.aspx.cs" Inherits="UI.ajaxHandler" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
    </form>
</body>
</html>

ajaxHandler.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Model;
using BLL;
namespace UI
{
    public partial class ajaxHandler : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DoingAJax();
            }
        }
        private void DoingAJax()
        {
            Response.Clear();
            //什么都没有的时候
            if (Request.QueryString["comm"] == null || Request.QueryString["comm"] == "")
            {
                Response.Write("0");
                Response.End();
                return;
            }

            string comm = (Request.QueryString["comm"].ToString());
            switch (comm)
            {
                case "Reg"://注册
                    RegUser();
                    break;
                case "Login"://登录
                    Login();
                    break;
                case "Logout"://注销
                    Logout();
                    break;
                case "getGoods"://获取商品信息 返回json
                    getGoods();
                    break;
                case "generateOrder"://提交订单保存session
                    generateOrder();
                    break;
                case "PaySuccess"://支付成功读取session保存订单数据库
                    PaySuccess();
                    break;
                case "isLogined"://是否登录
                    isLogined();
                    break;
                case "UserisExists"://判断用户名是否存在
                    UserisExists();
                    break;
                default:
                    Response.Write("0");
                    break;
            }
            Response.End();
        }
        public void PaySuccess()//先提交订单 保存订单session,然后支付成功的时候读取session存取数据库
        {
            //Session["Order_"]
            string strGID = Session["Order_GID"].ToString(); ;// Request.Form["GID"];
            string strUID = Session["Order_UID"].ToString();//Request.Form["UID"];
            string strPayed = Session["Order_Payed"].ToString(); //Request.Form["Payed"];
            string strCount = Session["Order_count"].ToString();// Request.Form["count"];
            string strAddress = Session["Order_Address"].ToString();// Request.Form["Address"];
            string strSize = Session["Order_Size"].ToString();// Request.Form["Size"];
            YC_Order order = new YC_Order();
            order.GID = Convert.ToInt32(strGID);
            order.UID = Convert.ToInt32(strUID);
            order.Price = Convert.ToDouble(strPayed);
            order.Count = Convert.ToInt32(strCount);
            order.Address = strAddress;
            order.GoodSize = strSize;
            ///存入数据库
            if (BLL.OrderBLL.generateOrder(order) == 1)
            {
                Response.Write("1");
            }
            else
            {
                Response.Write("0");
            }
        }
        public void generateOrder()
        {
            if (Session["UName"] == null)
            {
                Response.Write("0");

            }
            else {
                //传入商品ID 用户ID 已付资金,数量,地址,尺寸
                ///这里保存session等支付成功后 给支付页面用
                Session["Order_GID"] = Request.Form["GID"].ToString() ;
                Session["Order_UID"] = Request.Form["UID"].ToString();
                Session["Order_Payed"] = Request.Form["Payed"].ToString() ;
                Session["Order_count"] = Request.Form["count"].ToString() ;
                Session["Order_Address"] = Request.Form["Address"].ToString() ;
                Session["Order_Size"] = Request.Form["Size"].ToString(); ;
                //返回客户端
                    Response.Write("1");
           
                
            }
           
        }
        public void UserisExists()
        {
            string name = Request.QueryString["Name"].ToString();
            YC_User u = new YC_User();
            u.Name = name;
            if (BLL.UserBLL.isExists(u) == 1)
            {
                Response.Write("1");//存在
            }
            else {
                Response.Write("0");
            }
        }
        public void RegUser()
        {
            string name = Request.Form["Name"];
            string pwd = Request.Form["Pwd"];

            YC_User u = new YC_User();
            u.Name = name;
            u.Nickname = name;
            u.Password = pwd;
            u.Address = "四川";
            u.Sex = 0;
            u.Phone = "18381506390";
            u.Qq = "1031893464";
            int i = BLL.UserBLL.regUser(u);
            Response.Write(i);
        }
        public void isLogined()
        {
            if (Session["UName"] == null)
            {
                Response.Write("0");
            }
            else
            {

                Response.Write("1");
            }
        }
        public void Login()
        {
            string name = Request.Form["Name"];
            string pwd = Request.Form["Pwd"];
            YC_User u = new YC_User();
            u.Name = name;
            u.Password = pwd;
            if (BLL.UserBLL.login(u) == 1)
            {
                Session["UName"] = name;//登录成功写入Session
                Response.Write("1");
            }
            else {
                Response.Write("0");
            }
        }
        public void Logout()
        {
            Session["UName"] = null;
            Response.Write("1");//注销成功
        }
        public void getGoods()
        {
            if (Request.QueryString["GID"] == null)
            {
                Response.Write("{status:\"failure\"}");
            }
            else {
                int gid = Convert.ToInt32(Request.QueryString["GID"]);
                 YC_Goods goodobj= BLL.Goods.selectObjectById(gid);
                string allsize= goodobj.AllSize;
                string cxprice=goodobj.Cxprice.ToString();
                string goodname= goodobj.Name;
                string img1=goodobj.DesImg1Url;
                Response.Write("{status:\"success\",allsize:\""+allsize+"\",cxprice:\""+cxprice+"\",goodname:\""+goodname+"\",imgurl:\""+img1+"\"}");
            }
        }
    }
}

GoodsDetail.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="GoodsDetail.aspx.cs" Inherits="UI.GoodsDetail" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <title><%=_Name %>--商品详情</title>
    <script type="text/javascript" src="js/global.js" ></script>

<link rel="stylesheet" href="css/global.css" />
    <link href="css/product/productdetail0.css" rel="stylesheet" type="text/css" />
    <style>
	#picShow2{
		display: none;
	}
	#picShow3{
		display: none;
	}
</style>
    <script>
        function ffrequest()
        {
            alert("非法请求!");
        }
        function submitOrder()
        {
            //var checkValue=$("#select_id").val(); //获取选择项
        }
        //获取登录状态  打开订单Dlg
        function getGoodsInfo()
        {
            //  $('#ContactModal').modal('show');
            ///判断是否登录
            $.ajax({
                type: 'get',
                url: 'ajaxHandler.aspx?comm=isLogined',
                async:true,
                success: function (result) {
                    if (result == "1") {

                        $('#ContactModal').modal('show');
                    } else {
                        alert("您没登录!");
                    }
                }
            })
          
           

        }
          //异步获取数据给订单表单
        function getDlgData(gid)
        {
            $.ajax({
                type: 'get',
                url: 'ajaxHandler.aspx?comm=getGoods&GID=' + gid,
                async: true,
                // data: { Name: oNameText.value, Pwd: oPassText.value },
                success: function (result) {
                    var jsonObj = eval('(' + result + ')');
                    // alert(jsonObj);
                    var allsize = jsonObj.allsize;
                    var arrSizes = allsize.split("|");
                    for (i = 0; i < arrSizes.length; i++) {
                        // alert(arrSizes[i]);
                        //为select动态增加option
                        $('#selectSize').append($("<option/>", {
                            value: arrSizes[i],
                            text: arrSizes[i]
                        }));
                    }
                },
                error: function () {
                    alert('ERROR!');
                }
            });
        }
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <!--
    	置顶按钮开始
    -->
    <a name="topname"> </a>
	<div id="divtop"style="position: fixed;right:50px;top:80%;border:0;width:60px;height:60px;text-align: center;padding-top:20px;">
		<a href="#top" id="topa">
			<img src="../img/index/chevron-up.png" style="color:white;width:20px;"/>	
		</a>
	</div>
    <!--
    	置顶按钮结束
    -->
     <!--
    	联系购买对话框开始
    -->
    <div class="modal fade" id="ContactModal" role="dialog" aria-hidden="true" >
    	<div class="modal-dialog">
    		<div class="modal-content">
    			<div class="modal-header">
    				<button class="close" data-dismiss="modal" aria-hidden="true" type="button">
    					×
    				</button>
    				<h4 class="modal-title">
    					<img src="../img/1hycz.png" />   确认订单信息
    				</h4>
    			</div>
    			<!---中间开始--->
    			<div class="modal-body" >
    				<table class="table table-hover table-responsive table-bordered">
                        <tr>
                            <td>
                                商品名称:
                            </td>
                            <td>
                                <label>steelsir 时尚长袖拼接宽松衬衫</label>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                尺码:
                             </td>
                            <td>
                                <select id="selectSize">
                                    
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                数量:
                            </td>
                            <td>
                                <input type="text" id="inputCount" />
                            </td>
                        </tr>
                        <tr>
                         <td>
                            邮编:
                        </td>
                        <td>
                            <input type="text" id="emailnum"/>
                        </td>
                            </tr>
                         <tr>
                            <td>
                                收件人:
                            </td>
                            <td>
                                <input type="text" id="inPeople" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                手机号码:
                            </td>
                            <td>
                                <input type="text" id="inphone" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                收货地址:
                            </td>
                            <td>
                                <textarea id="addressarea" ></textarea>
                            </td>
                        </tr>
                       
    				</table>
    			</div><!---中间结束----->
    			
    			<div class="modal-footer">
    			  <button class="btn btn-danger" id="btnGenerateOrder" onclick="return false;<%/*所有btn默认会回传 这里取消回传*/ %>" >提交订单</button> 	<button class="btn btn-default" data-dismiss="modal">关闭</button>
    			</div>
    			<!----->
    		</div>
    	</div>
    </div>
    <script>
        var obtnGenerateOrder = document.getElementById("btnGenerateOrder");
        obtnGenerateOrder.onclick = function ()
        {
            var gid =<%=_GID%>; //这里直接替换后台属性
            var selectSize = $("#selectSize").val();
            var inputcount = document.getElementById("inputCount").value;
            var emailnum = document.getElementById("emailnum").value;
            var peoplename = document.getElementById("inPeople").value; 
            var inphone = document.getElementById("inphone").value;
            var address = $("#addressarea").val();
            var totaladdress = address +"    "+ peoplename +"    "+ inphone+"    "+ emailnum;
            var payd =<%=_CXPrice%> * inputcount;
            // alert(address);
            $.ajax({
                url: "ajaxHandler.aspx?comm=generateOrder",
                type: 'post',
                data: {
                    GID: gid,
                    UID:<%=_UID%>,
                    Payed: payd,
                    count: inputcount,
                    Address: totaladdress,
                    Size: selectSize,
                  },
                success: function (result)
                {
                    //alert(result);
                    location.href = "Paying.aspx";
                }
            })
           // alert("点击了这里");
     

            return false;//禁止回传(非常重要)
        }
    </script>
    <!--
    	联系购买对话框结束
    -->
    
        	<div style="width:950px;margin:0 auto;">
            	<div id="ling01">
            		<div style="width:420px;height:560px;overflow: hidden;">
            			<img id="picShow1"  src="productImg/<%=_DesImg1Url %>"" />
            			<img id="picShow2"  src="productImg/<%=_DesImg2Url %>" />
            			<img id="picShow3" src="productImg/<%=_DesImg3Url %>" />
            		</div>
            			
            	</div>
              <div id="ling02">  
                <div id="ling03"><img id="picChange1"src="productImg/<%=_DesImg1Url %>""   width="45" height="60"/></div>
                <div id="ling03"><img id="picChange2"src="productImg/<%=_DesImg2Url %>""  width="45" height="60" /></div>
                <div id="ling03"><img id="picChange3" src="productImg/<%=_DesImg3Url %>""  width="45" height="60"/></div>
              </div>
              <script>
                  //1031893464@qq.com
                  var oPicC1 = document.getElementById("picChange1");
                  var oPicC2 = document.getElementById("picChange2");
                  var oPicC3 = document.getElementById("picChange3");
                  var oPicShow = document.getElementById("picShow");
                  oPicC1.onmouseover = function () {
                      $("#picShow3").fadeOut();
                      $("#picShow2").fadeOut();
                      $("#picShow1").fadeIn('slow');
                  };
                  oPicC2.onmouseover = function () {
                      $("#picShow1").fadeOut();
                      $("#picShow3").fadeOut();
                      $("#picShow2").fadeIn('slow');
                  };
                  oPicC3.onmouseover = function () {
                      $("#picShow1").fadeOut();
                      $("#picShow2").fadeOut();
                      $("#picShow3").fadeIn('slow');
                  };
              </script>
           </div>
          <div id="ling12">
            	<div id="ling04"><%=_Name %></div>
                <div id="ling05">THETHING</div>
                <div id="ling06">市场价: ¥<%=_SCPrice %></div>
                <div id="ling07">促销价:<label id="heiti">¥<%=_CXPrice %></label></div>
                <div id="ling08"></div>
              <div id="ling09"><img src="../img/product/productdetail0/ad0.png" /></div>
             <!-- <div id="ling16"></div>-->
              <div>
                  <a href="#" onclick="javascript:getDlgData(<%=_GID %>);getGoodsInfo();"><img src="img/product/productdetail0/lijigoumai.jpg"  /></a>
              </div>
    <!---->         <!-- <div id="ling14" ><a href="#" id="btnliji" onclick="javascript:$('#ContactModal').modal('show');"><img src="../img/product/productdetail0/lijigoumai.jpg"  /></a></div>-->
            <!--  <div id="ling15"><img src="img/product/productdetail0/collect.png" /></div>-->
            <!--<div id="ling13">分享到:</div>-->
            <div id="ling17">
            	<ul id="ling10">
                 	<li id="ling11"><img src="../img/product/productdetail0/qq-icon.png" /></li>
                    <li id="ling11"><img src="../img/product/productdetail0/weibo.png" /></li>
                    <li id="ling11"><img src="../img/product/productdetail0/weixin.png" /></li>
                    <li id="ling12"><img src="../img/product/productdetail0/dou.png" /></li>
                    <li id="ling11"><img src="../img/product/productdetail0/txweibo.png" style="position:relative ;top:1px;"/></li>
                    <li id="ling11"><img src="../img/product/productdetail0/kongjian.png" style="position:relative ;top:-3px;"/></li>
                    <li id="ling12"><img src="../img/product/productdetail0/renren.png" style="position:relative ;top:3px;"/></li>                
                 </ul>
            </div> 
    </div>
         <div>
         <div id="ling19">尺码信息SIZE INFO</div>
         <div id="ling20"><table>
         	<tr id="ling21">
            	<td>吊牌尺码</td>
                <td>参考尺码</td>
                <td>肩宽</td>
                <td>胸围</td>
                <td>袖长</td>
                <td>前衣长</td>
                <td>后衣长</td>
            </tr>
            <tr>
            	<td>S</td>
                <td>155/80A</td>
                <td>51</td>
                <td>112</td>
                <td>47</td>
                <td>89</td>
                <td>96</td>
            </tr>
         	<tr>
            	<td>M</td>
                <td>160/84A</td>
                <td>52</td>
                <td>116</td>
                <td>49</td>
                <td>91</td>
                <td>98</td>
            </tr>
            <tr>
            	<td>L</td>
                <td>165/88A</td>
                <td>54</td>
                <td>124</td>
                <td>50</td>
                <td>94</td>
                <td>101</td>
            </tr>
         </table></div>
         <div id="ling22">※ 以上尺寸为实物人工测量,因测量方式不同会有1-2CM误差,相关数据仅作参考,以收到实物为准。 单位:CM</div>
         <div id="ling23">※ 参考尺码因衣服版型、剪裁不同会有误差,仅供参考</div>
         <div id="ling24"><img src="../img/product/productdetail0/1.jpg" /></div>
      <%--   <div id="ling25"></div>
         <div id="ling26">商品详情 DETAILS</div>
         <div id="ling27">THETHING 成立于2005年上海,品牌标签:独立态度、好玩、graphic&design... “THETHING”解释为“这东西”。没有所谓具体的含义,街头服饰的产品结构,玩乐、戏谑的精神在开发中一脉相承。生活中有好东西,太贵;也有便宜货,却太随便。把“THETHING”磨合的又讲究价格又亲和是我们追寻的目标。</div>
       <div id="ling28">
		<ul id="ling29">
        	<li><img src="../img/product/productdetail0/p1.jpg" /></li>
            <li><img src="../img/product/productdetail0/p2.jpg" /></li>
            <li><img src="../img/product/productdetail0/p3.jpg" /></li>
            <li><img src="../img/product/productdetail0/p4.jpg" /></li>
            <li><img src="../img/product/productdetail0/p5.jpg" /></li>
            <li><img src="../img/product/productdetail0/p6.jpg" /></li>
            <li ><img src="../img/product/productdetail0/p7.jpg" /></li>
            <li><img src="../img/product/productdetail0/p8.jpg" /></li>
            <li><img src="../img/product/productdetail0/p9.jpg" /></li>
            <li><img src="../img/product/productdetail0/p10.jpg" /></li>
            <li><img src="../img/product/productdetail0/p11.jpg" /></li>
            <li><img src="../img/product/productdetail0/p12.jpg" /></li>
            <li><img src="../img/product/productdetail0/p13.jpg" /></li>
            <li><img src="../img/product/productdetail0/p14.jpg" /></li>
            <li><img src="../img/product/productdetail0/p15.jpg" /></li>
            <li><img src="../img/product/productdetail0/p16.jpg" /></li>
        </ul>--%>
             <%=_Detail %>
       </div>
       <div id="ling30"><img src="../img/product/productdetail0/l123.png" /></div>
       <div id="ling31"></div>
         


 <div style="clear:both;"></div>
               
</asp:Content>
GoodsDetail.aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using BLL;
namespace UI
{
    public partial class GoodsDetail : System.Web.UI.Page
    {
        //商品ID
        public int _GID;
        //当前用户uid
        public int _UID;
        //商品名称
        public string _Name;
        //促销价
        public string _CXPrice;
        //市场价
        public string _SCPrice;
        //描述图片
        public string _DesImg1Url;
        public string _DesImg2Url;
        public string _DesImg3Url;
        //尺寸
        public string _AllSize;
        //详细描述
        public string _Detail;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                if (Request.QueryString["GID"] == null)
                {
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "GG", "<SCRIPT>ffrequest();</SCRIPT>");
                    return;
                }
                if (Session["UName"] != null)
                {
                    this._UID = BLL.UserBLL.selectIDByName(Session["UName"].ToString());
                }
                this._GID = Convert.ToInt32(Request.QueryString["GID"]);
                DataTable dt = BLL.Goods.selectOneByID(_GID);
                DataRow dr = dt.Rows[0];
                _Name = dr["Name"].ToString();
                _CXPrice = dr["CXPrice"].ToString();
                _SCPrice = dr["SCPrice"].ToString();
                _DesImg1Url = dr["DesImg1Url"].ToString();
                _DesImg2Url = dr["DesImg2Url"].ToString();
                _DesImg3Url = dr["DesImg3Url"].ToString();
                _AllSize = dr["AllSize"].ToString();
                _Detail = dr["DetailImages"].ToString();

            }

        }
    }
}
关于防止Button回传,只需要在客户端事件OnClientClick里面加一句 return false;即可。
相关文章
相关标签/搜索