boboJQuery实现Ajax 根据商品名称自动显示价格

数据库字段:Id(主键,自增),Name(商品名称),Price(商品单价)

添加数据集DataSetProducts ,添加方法:GetDataByName()

----->对应SQL:

SELECT id, name, price FROM dbo.T_Product
where name = @name

 

 新建一般处理程序:GetPrice.ashx

代码:

 

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AJAX.DataSetProductsTableAdapters;

namespace AJAX
{
    /// <summary>
    /// GetPrice 的摘要说明
    /// </summary>
    public class GetPrice : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string name = context.Request["name"];

            var data = new T_ProductTableAdapter().GetDataByName(name); //调用DataSet中的方法
            if (data.Count <= 0)
            {
                context.Response.Write("none|0");   //竖线左边是返回状态,右边是价格
            }
            else
            {
                context.Response.Write("ok|" + data.Single().price); //我们自己定义的协议格式 ok可以换成其他的字符串;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
复制代码

Html页面代码:

复制代码
<!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>
    <title>Ajax完成查询价格</title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(function () {
            $("#Text1").blur(function () {
                var name = $("#Text1").val();
                $.post("GetPrice.ashx", { "name": name }, function (data, statusText) {
                    if (statusText == "success") {
                        var atts = data.split("|");
                        if (atts[0] == "ok") {   //atts[0]是参数;表示状态;  
                            $("#Text2").val(atts[1]); //atts[1]是参数,表示价格;
                        } else if (atts[0] == "none") {
                            $("#Text2").val("没有这个商品");
                        } else {
                            alert("返回格式错误");
                        }
                    } else {
                        alert("Ajax错误!");
                    }
                });
            });
        });
    </script>
</head>
<body>
    查询名称:<input id="Text1" type="text" /><br />
    <br />
    价&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;格:<input id="Text2" type="text" />
</body>
</html>
复制代码

转载于:https://www.cnblogs.com/nice41/p/3831983.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值