关于ajax 和josn

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
     <script type="text/javascript" src="js/jquery-1.4.1.js"></script>
    <script type="text/javascript">
        // 创建一个基于web浏览器的XMLHttpRequest对象
        function createXHR() {

            // 检查是否支持XMLHttpRequest.
            if (typeof XMLHttpRequest != "undefined") {
                return new XMLHttpRequest();
            }

            // IE6和老版本
            else if (typeof ActiveXObject != "undefined") {
                if (typeof arguments.callee.activeXString != "string") {
                    var versions = [
        "MSXML2.XMLHttp6.0",
        "MSXML2.XMLHttp3.0",
        "MSXML2.XMLHttp"];

                    for (var i = 0; i < versions.length; i++) {
                        try {
                            var xhr = new ActiveXObject(versions[i]);
                            arguments.callee.activeXString = versions[i];
                            return xhr;
                        }
                        catch (ex) {
                            throw new Error(ex.toString());
                        }
                    }
                    return new ActiveXObject(arguments.callee.activeXString);
                }
                else {
                    throw new Error("No XHR object available");
                }

            }
            return null;
        }

        jQuery(document).ready(function () {
            jQuery("#btnAjax").click(function () {
                alert('123.....');
                GetDataFromServer();
            });

        });

        function GetDataFromServer() {

            // 创建XmlHttqRequest对象.
            var req = new createXHR();
            if (req != null) {
                req.onreadystatechange = function () {
                    if (req.readyState == 4) {
                        if ((req.status >= 200 && req.status < 300) || req.status == 304) {
                            alert(req.responseText);//弹出
                            var jsonTextDiv = document.getElementById("jsonText");

                            // Deserializes JavaScript Object Notation (JSON) text to produce a JavaScript value.
                            var data = JSON.parse(req.responseText);
                            for (var i = 0; i < data.length; i++) {
                                var item = data[i];
                                var div = document.createElement("div");
                                div.setAttribute("class", "dataItem");
                                // Inserts data into the html.
                                div.innerHTML = item.Name + " sold " + item.Qty + "; Product number: " + item.SerialNumber;
                                jsonTextDiv.appendChild(div);//追加
                            }
                        }
                        else {
                            alert("Request was unsuccessful: " + req.status);
                        }
                    }
                };

                // Sends a asyn request. 
                req.open("GET", "Handler.ashx", true);
                req.send(null);
            }
        }


      
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="AjaxJosn" id="btnAjax" />
    </div>
    <div id="jsonText"></div>
    </form>
</body>
</html>

//下面是一般处理程序代码

 public class Handler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            var manage = new ProductManager();
            var products = manage.GetAllProducts(); //返回一个对象
            var json = new DataContractJsonSerializer(products.GetType()); //DataContractJsonSerializer需要添加引用using System.Runtime.Serialization
            json.WriteObject(context.Response.OutputStream, products);
        }

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

 //两个类文件

 public class ProductDao
    {
        public ProductDao()
        { 
        
        }
        /// <summary>
        /// 得到产品ID
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// 得到产品名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 得到产品序列号
        /// </summary>
        public string SerialNumber { get; set; }
        /// <summary>
        /// 得到产品数量
        /// </summary>
        public int Qty { get; set; }

    }

 

 public class ProductManager
    {
       public string _connectionString = ConfigurationManager.AppSettings["ConnectionString"];   
        private string Query = "SELECT [ID], [Name], [SerialNumber], [Qty] FROM  ProductDao"; //创建查询语句
        private IList<ProductDao> _products = new List<ProductDao>(); //创建泛型接口列表
        public IList<ProductDao> GetAllProducts()
        {
            using (var con = new SqlConnection(_connectionString))
            {
                
                using (var com = new SqlCommand(Query,con))
                {
                    con.Open();
                    using (var reader = com.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        while (reader.Read())
                        {
                            var product = new ProductDao
                            {
                                Id = (int)reader["ID"],
                                Name = (string)reader["Name"],
                                SerialNumber = (string)reader["SerialNumber"],
                                Qty = (int)reader["Qty"]
                            };
                            _products.Add(product);
                        }
                    }
                }
            }

            return _products; //返回例表集合对象

        }

    }

 

 
posted @ 2012-11-17 15:33  KyrieYang  阅读(996)  评论(0编辑  收藏  举报