AJAX练习

1,填入商品名称,自动带出价格

表T_Products

Id  Name  Price

1  电脑  1000

2  IPad  2000

3  笔记本  3000

数据集DataSet1.xsd

T_Products

Id

Name

Price

T_ProductsTableAdapter

Fill,GetData()

GetDataByName(@Name)

一般处理程序GetPrice.ashx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebApplication1.DataSet1TableAdapters;

namespace WebApplication1
{
    /// <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_ProductsTableAdapter().GetDataByName(name);
            if (data.Count<=0)
            {
                context.Response.Write("none|0");
            }
            else
            {
                context.Response.Write("ok|"+data.Single().Price);
            }
            //context.Response.Write("Hello World");
        }

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

Html页面Products.Htm

<!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></title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#Text1").blur(function () {//光标移开后
                var name = $("#Text1").val();

               //向服务器的GetPrice.ashx发出POST请求,带参数name,根据状态status,返回数据data
                $.post("GetPrice.ashx", { "name": name }, 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("返回数据格式错误");
                        }
                    }
                    else {
                        alert("ajax失败")
                    }
                })
            })
        })
    </script>
</head>
<body>
    <input id="Text1" type="text" />
    <input id="Text2" type="text" />
</body>
</html>

 

posted @ 2012-10-07 17:07  joesphos  阅读(220)  评论(0)    收藏  举报

如果您认为这篇文章还不错或者有所收获,您可以打赏点哦,多多少少没关系,一分一毫也是对我的支持和鼓励。谢谢您!