Jquery读取.Net WebService Json数据

简介:

鉴于上篇文章中提到的Json优点:易读性、可扩展性和操作方便,接下来我们实现一个简单的例子Demo,场景是:查询商品信息;实现过程:Web程序通过Jquery调用WebService,Web Service返回Json对象,成功调用后,对返回的JSon结果进行处理,下面我们看一下具体实现过程:

1、 首先创建一个Aap.net web 应用程序,如下图:

 

2、 添加实体类Product.cs到工程中,并且序列化,代码如下

[Serializable]

    public class Product

    {

        public long ProductId { getset; }

        public string ProductName { getset; }

        public decimal Price { getset; }

        public int Stock { getset; }

    }

 

 

3、 添加数据类ProductData.cs类到工程中,此类主要完成数据的查询操作,代码如下所示:

public class ProductData

    {

        private List<Product> productList = new List<Product>()

        {

            new Product(){ProductId=1,ProductName="笔记本", Price=10000M, Stock=10},

            new Product(){ProductId=2,ProductName="格子绒长袖衬衫", Price=90M, Stock=20},

            new Product(){ProductId=3,ProductName="纯棉长袖T恤", Price=99M, Stock=40},

            new Product(){ProductId=4,ProductName="炫彩T恤", Price=67M, Stock=30},

            new Product(){ProductId=5,ProductName="直筒裤男牛仔裤", Price=100M, Stock=20},

             new Product(){ProductId=6,ProductName="[无印严选]纯色V领长袖T恤", Price=67M, Stock=50},

            new Product(){ProductId=7,ProductName="英伦学院派马夹", Price=44M, Stock=40},

            new Product(){ProductId=8,ProductName="纯棉连帽宽松卫衣", Price=66M, Stock=30},

            new Product(){ProductId=9,ProductName="纯棉多口袋工装裤", Price=80M, Stock=990},

            new Product(){ProductId=10,ProductName="假两件长袖T恤", Price=89M, Stock=30},

        };

        /// <summary>

        /// 查询所有商品

        /// </summary>

        /// <returns>所有商品</returns>

        public List<Product> GetProducts()

        {

            return productList;

        }

        /// <summary>

        /// 根据商品Id查询商品

        /// </summary>

        /// <param name="id">商品编号</param>

        /// <returns>商品</returns>

        public Product GetProductById(long id)

        {

            return productList.FirstOrDefault(p => p.ProductId == id);

        }

        /// <summary>

       /// 根据商品名称查询商品

        /// </summary>

        /// <param name="id">商品名称</param>

        /// <returns>商品</returns>

        public List<Product> GetProductByName(string name)

        {

            return productList.Where(p => p.ProductName == name).ToList();

        }

 

4、 添加ASP.NET Web Service 到工程中,命名为ProductServic.asmx,如下图:

 

此Web Service调用ProductData类,完成数据查询操作,具体代码如下:

    /// <summary>

    /// Summary description for ProductService

    /// </summary>

    [WebService(Namespace = "http://tempuri.org/")]

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    [System.ComponentModel.ToolboxItem(false)]

    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

   [System.Web.Script.Services.ScriptService]

    public class ProductService : System.Web.Services.WebService

    {

 

        private ProductData dataSource

        {

            get

            {

                return new ProductData();

            }

        }

 

        /// <summary>

        /// Get the Products

        /// </summary>

        /// <returns></returns>

        [WebMethod]

        [ScriptMethod(ResponseFormat=ResponseFormat.Json,UseHttpGet=true)]

        public List<Product> GetProducts()

        {

            return dataSource.GetProducts();

        }

 

        /// <summary>

        /// 根据商品Id查询商品

        /// </summary>

        /// <param name="object">商品编号</param>

        /// <returns>商品</returns>

        [WebMethod]

        [ScriptMethod(ResponseFormat=ResponseFormat.Json,UseHttpGet=true)]

        public Product GetProductById(object id)

        {

            Product p = null;

            if (id!=null)

            {

                int productId = 0;

                int.TryParse(id.ToString(),out productId);

                p = dataSource.GetProductById(productId);

            }

            return p;

        }

 

        /// <summary>

        /// 根据商品名称查询商品

        /// </summary>

        /// <param name="id">商品名称</param>

        /// <returns>商品</returns>

        [WebMethod]

        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]

        public List<Product> GetProductById(string name)

        {

            return dataSource.GetProductByName(name);

        }

    }    }

注:

Ø 引用命名空间:System.Web.Script.Services.ScriptService

Ø 给方法添加注解:[ScriptMethod(ResponseFormat = TheResponseFormat, UseHttpGet = true/false)]

ResponseFormat:方法要返回的类型,一般为Json或者XML

UseHttpGet:true表示“Get”可以访问此方法

5、 在Defualt.aspx页面引用Jquery类库

引用Google网络jquery 类库http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js

或者本地类库<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>

6、 在Defualt.aspx页添加如下HTML代码:

<div id="listContainer" class="container">

        <div id="title">

            Product List</div>

        <table id="productList">

            <thead>

            </thead>

            <tbody>

            </tbody>

        </table>

</div>

Jquery会动态向id=ProductList的Table中添加查询到的数据

7、 在Defualt.aspx页添加如下样式代码:

 <style type="text/css">

        body

        {

            font-familyVerdana,Arial;

        }

        .container

        {

            widthauto;

            padding1.5em;

            margin1em;

        }

        .container #title

        {

            font-size2em;

            width100%;

            border-bottomgroove 0.5em blue;

        }

        #productList

        {

            width100%;

            border-collapsecollapse;

        }

        #productList td

        {

            padding1em;

            border-stylesolid;

            border-width1px;

            border-colorBlue;

            margin0;

        }

        thead td

        {

            background-colorYellow;

        }

        tbody tr:hover

        {

            background-color#aaa;

        }

   </style>

 

8、 使用Jquery的Ajax方法调用Web Service中方法,代码如下:

$(document).ready(function () {

            // Get Product list        

            $.ajax({

                type: "GET",

                contentType: "application/json; charset=utf-8",

                url: "ProductService.asmx/GetProducts",

                dataType: "json",

                success: insertCallback,

                error: errorCallback

            });

        function insertCallback(result) {

            $("#productList").find("tr:gt(0)").remove();

            if (result["d"].length > 0) {

                $('#productList > thead:last').append('<tr><td>商品名称</td><td>价格</td><td>库存量</td></tr>');

            }

            for (var i = 0; i < result["d"].length; i++) {

                var product = eval(result["d"][i]);

                $('#productList > tbody:last').append('<tr onclick="ShowDetail(' + product.ProductId + ')"><td>' +

                product.ProductName + '</td><td>' +

                product.Price + '</td><td>' +

                product.Stock + '</td></tr>');

            }

        }

        function errorCallback(XMLHttpRequest, textStatus, errorThrown) {

            alert(errorThrown + ':' + textStatus);

        }

注:

$.ajax方法有以下属性:

Type:    HTTP请求方法,在做查询操作时,经常用Get方法

contentType:在请求头部的类型,由于Web Service返回Json对象,此处值为:application/json; charset=utf-8

url:求的URL地址

dataTyep:定义返回的类型

Success:调用成功时,要执行的方法

error:调用失败是,要执行的方法

9、 执行程序,效果如下:

 

至此,使用Jquery查询Web Service返回的JSon对象已经完成

源代码下载地址:http://files.cnblogs.com/ywqu/JsonWebService.rar










本文转自 灵动生活 51CTO博客,原文链接:http://blog.51cto.com/smartlife/451376,如需转载请自行联系原作者

目录
相关文章
|
1月前
|
存储 JSON Apache
揭秘 Variant 数据类型:灵活应对半结构化数据,JSON查询提速超 8 倍,存储空间节省 65%
在最新发布的阿里云数据库 SelectDB 的内核 Apache Doris 2.1 新版本中,我们引入了全新的数据类型 Variant,对半结构化数据分析能力进行了全面增强。无需提前在表结构中定义具体的列,彻底改变了 Doris 过去基于 String、JSONB 等行存类型的存储和查询方式。
揭秘 Variant 数据类型:灵活应对半结构化数据,JSON查询提速超 8 倍,存储空间节省 65%
|
1天前
|
JSON 数据可视化 定位技术
python_将包含汉字的字典数据写入json(将datav的全省数据中的贵州区域数据取出来)
python_将包含汉字的字典数据写入json(将datav的全省数据中的贵州区域数据取出来)
5 0
|
14天前
|
存储 JSON JavaScript
「Python系列」Python JSON数据解析
在Python中解析JSON数据通常使用`json`模块。`json`模块提供了将JSON格式的数据转换为Python对象(如列表、字典等)以及将Python对象转换为JSON格式的数据的方法。
31 0
|
18天前
|
存储 JSON 数据挖掘
python逐行读取txt文本中的json数据,并进行处理
Python代码示例演示了如何读取txt文件中的JSON数据并处理。首先,逐行打开文件,然后使用`json.loads()`解析每一行。接着,处理JSON数据,如打印特定字段`name`。异常处理包括捕获`JSONDecodeError`和`KeyError`,确保数据有效性和字段完整性。将`data.txt`替换为实际文件路径运行示例。
14 2
|
1月前
|
JSON 数据格式
糊涂工具类(hutool)post请求设置body参数为json数据
糊涂工具类(hutool)post请求设置body参数为json数据
61 1
|
1月前
|
JSON 前端开发 数据格式
Ajax传递json数据
Ajax传递json数据
11 0
|
1月前
|
JSON 并行计算 API
使用CJSON/Nlohmann:快速简便地在C/C++中处理JSON数据
使用CJSON/Nlohmann:快速简便地在C/C++中处理JSON数据
148 0
|
1月前
|
JSON 数据格式 Python
Python生成JSON数据
Python生成JSON数据
23 0
|
1月前
|
XML 开发框架 .NET
C# .NET面试系列八:ADO.NET、XML、HTTP、AJAX、WebService
## 第二部分:ADO.NET、XML、HTTP、AJAX、WebService #### 1. .NET 和 C# 有什么区别? .NET(通用语言运行时): ```c# 定义:.NET 是一个软件开发框架,提供了一个通用的运行时环境,用于在不同的编程语言中执行代码。 作用:它为多语言支持提供了一个统一的平台,允许不同的语言共享类库和其他资源。.NET 包括 Common Language Runtime (CLR)、基础类库(BCL)和其他工具。 ``` C#(C Sharp): ```c# 定义: C# 是一种由微软设计的面向对象的编程语言,专门为.NET 平台开发而创建。 作
174 2
|
1月前
|
JSON 数据可视化 Linux
数据可视化工具JSON Crack结合内网穿透实现公网访问
数据可视化工具JSON Crack结合内网穿透实现公网访问
数据可视化工具JSON Crack结合内网穿透实现公网访问