AJAX校验商品价格(类似校验用户名)

ASP.NET AJAX获取价格示例
本文介绍了一个使用ASP.NET的服务器端程序处理AJAX请求的例子。该程序通过客户端发送的商品名称请求,从数据库中获取商品的价格并返回给客户端显示。示例包括完整的服务器端处理代码和客户端页面代码。

服务器端程序

567993-20160316215005053-2040328880.png
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ WebHandler Language="C#" Class= "GetPrice" %>
 
using System;
using System.Web;
 
public class GetPrice : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context .Response.ContentType = "text/plain";
        string name = context.Request ["name"];
        
        DataSetProductsTableAdapters .T_ProductsTableAdapter priceadapter=new DataSetProductsTableAdapters .T_ProductsTableAdapter();
        DataSetProducts .T_ProductsDataTable prices = priceadapter.GetDataByName(name);
        if ( prices.Count <=0)
        {
            context .Response.Write("none|0" );
        }
        else
        {
            DataSetProducts .T_ProductsRow price = prices[0 ];
            context .Response.Write("ok|" +Convert.ToString(price .Price));
        }
    }

客户端页面代码

567993-20160316215005490-1765017159.png
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<script type="text/javascript">
        $( function () {
            $( "#Text1").blur(function () {
                var sname = $("#Text1" ).val();
                $.post( "GetPrice.ashx", { name: sname }, function (data, status) {
                    if (status == "success" ) {
                        var arrs = data.split("|" );
                        if (arrs[0] == "ok" ) {
                            $( "#Text2").val(arrs[1]);
                        }
                        else if (arrs[0] == "none") {
                            alert( "没有该商品" );
                        }
                        else {
                            alert( "AJAX错误");
                        }
                    }
                    else {
                        alert( "wrong");
                    }
 
                });
            });
        })
    </script >
 
<body>
 
    <p >
        <input id="Text1" type="text" />
        <input id="Text2" type="text" /></p>
 
</body>
</html>

测试效果

567993-20160316215006334-1797946647.gif

转载于:https://www.cnblogs.com/zhxshseu/p/5285353.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值