使用JQuery + JSON 调用Web Service

来源:互联网 发布:淘宝全球购物网 编辑:程序博客网 时间:2024/05/22 06:26

近两天看了不少使用 JQuery + JSON 调用Web Service 的文章,现总结如下:


一,Web Service 部分

目前发现两种试的写法,具体如下:

* 两者的共同点:

1, 均需要使用到 System.Web.Extensions ,故必须使用使用 VS2008 或 VS2010 或以上。

2, 所需引用:

using System;using System.Collections.Generic;using System.Web;using System.Web.Services;using System.Web.Script.Services;using System.Web.Script.Serialization;
3,Web Service 声明:

namespace JSONDemo{    /// <summary>    /// Summary description for Service1    /// </summary>    [WebService(Namespace = "http://tempuri.org/")]    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]    [System.ComponentModel.ToolboxItem(false)]    [ScriptService]    public class JSONService : System.Web.Services.WebService    {
注意点:必须要有[ScriptService] 的属性声明!

* 两者的区别,在Web Method中的不同:

1, 普通正常的XML 输出方式:* 此方式中无需声明输出格式,故和普通Web Method 方式没有什么不同

        [WebMethod]        public Employee[] TestXML()        {            Employee[] e = new Employee[2];            e[0] = new Employee();            e[0].Name = "Ajay Singh";            e[0].Company = "Birlasoft Ltd.";            e[0].Address = "LosAngeles California";            e[0].Phone = "310-235-1535";            e[0].Country = "US";            e[1] = new Employee();            e[1].Name = "Ajay Singh";            e[1].Company = "Birlasoft Ltd.";            e[1].Address = "D-195 Sector Noida";            e[1].Phone = "120-467500";            e[1].Country = "India";            return e;        }

2, 直接格式化为 JSON 的输出方式:* 此方式中 JSON 格式必须显式声明,对 XML 格式也可显式声明,也可不声明

* 对 JSON 显式声明的方式,注意: 

a,  输出类型必须为 :string ;  

b,  必须使用 System.Web.Script.Serialization 中的 JavaScriptSerializer().Serialize() 方法对 Object 进行序列化处理。

        [WebMethod]        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]        public string TestJSON()        {            Employee[] e = new Employee[2];            e[0] = new Employee();            e[0].Name = "Ajay Singh";            e[0].Company = "Birlasoft Ltd.";            e[0].Address = "LosAngeles California";            e[0].Phone = "1204675";            e[0].Country = "US";            e[1] = new Employee();            e[1].Name = "Ajay Singh";            e[1].Company = "Birlasoft Ltd.";            e[1].Address = "D-195 Sector Noida";            e[1].Phone = "1204675";            e[1].Country = "India";            return new JavaScriptSerializer().Serialize(e);        }        [WebMethod]        [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]        public Employee[] TestXML()        {            Employee[] e = new Employee[2];            e[0] = new Employee();            e[0].Name = "Ajay Singh";            e[0].Company = "Birlasoft Ltd.";            e[0].Address = "LosAngeles California";            e[0].Phone = "310-235-1535";            e[0].Country = "US";            e[1] = new Employee();            e[1].Name = "Ajay Singh";            e[1].Company = "Birlasoft Ltd.";            e[1].Address = "D-195 Sector Noida";            e[1].Phone = "120-467500";            e[1].Country = "India";            return e;        }

二,  JQuery + JSON 客户端调用部分

一,对于未有任何显式声明的 WebMethod ,在使用时不可使用 dataType: "json" 属性声明,如下:

* 注意:

1,使用 msg 的方式来读取Web Service 的返回字串:data = eval("(" + msg + ")");

2,使用 Data.d 的方式来获取真正的Class 数组 (此Class 并非和原始定义的Class 一致,而会自动多出一个"__type" 属性,但一般无需使用。


function testJson() {    $.ajax({        type: "POST",        url: "JSON.asmx/TestJSON",        data: "{}",        contentType: "application/json; charset=utf-8",        // dataType: "json",     // 如未显式声明为 JSON ,则不可使用此属性        success: function(msg) {            var data = eval("(" + msg + ")");            var t = "<table border=1> <tr>" +              "<td> <strong>Name</strong></td> <td> " +              "<strong>Company</strong></td> <td> " +              "<strong>Address</strong></td> <td> " +              "<strong>Phone</strong></td> <td> " +              "<strong>Country</strong></td> </tr> ";            jQuery.each(data.d, function(rec) {                t = t + " <tr> <td> " + this.Name + "</td> <td> " +                    this.Company + "</td> <td> " + this.Address +                     "</td> <td> " + this.Phone +                      "</td> <td> " + this.Country +                      "</td> </tr> ";            });            t = t + " </table> ";            $("#jsonDiv").html(t);        },        error: function(msg) {        }    });};

注意:此时 msg.d 的格式和内容如下:

{"d":[{"__type":"JSON_Demo.Employee","Name":"Ajay Singh","Company":"Birlasoft Ltd.","Address":"LosAngeles California","Phone":"310-235-1535","Country":"US"},{"__type":"JSON_Demo.Employee","Name":"Ajay Singh","Company":"Birlasoft Ltd.","Address":"D-195 Sector Noida","Phone":"120-467500","Country":"India"}]}



二,对于使用显式声明为 JSON 的 WebMethod ,在使用时可使用 dataType: "json" , 如下:

* 注意:

1, 必须使用 msg.d 的方式来读取 JSON 字串 data = eval("(" + msg.d + ")");

2, 之后可直接使用 data 作为 Class 来使用。

function testJson() {    $.ajax({        type: "POST",        url: "JSON.asmx/TestJSON",        data: "{}",        contentType: "application/json; charset=utf-8",        dataType: "json",        success: function(msg) {            var data = eval("(" + msg.d + ")");            var t = "<table border=1> <tr>" +              "<td> <strong>Name</strong></td> <td> " +              "<strong>Company</strong></td> <td> " +              "<strong>Address</strong></td> <td> " +              "<strong>Phone</strong></td> <td> " +              "<strong>Country</strong></td> </tr> ";            jQuery.each(data, function(rec) {                t = t + " <tr> <td> " + this.Name + "</td> <td> " +                    this.Company + "</td> <td> " + this.Address +                     "</td> <td> " + this.Phone +                      "</td> <td> " + this.Country +                      "</td> </tr> ";            });            t = t + " </table> ";            $("#jsonDiv").html(t);        },        error: function(msg) {        }    });};
对应的显示结果如下:

注意:此时 msg.d 的格式和内容如下:

[{"Name":"Ajay Singh","Company":"Birlasoft Ltd.","Address":"LosAngeles California","Phone":"1204675","Country":"US"},{"Name":"Ajay Singh","Company":"Birlasoft Ltd.","Address":"D-195 Sector Noida","Phone":"1204675","Country":"India"}]



三,对于使用显式声明为 XML 的 WebMethod ,目前暂时未发现使用 JSON 方式处理的方法。


参考:

以上例子中使用的 Class : 

public class Employee{    public string Name { get; set; }    public string Company { get; set; }    public string Address { get; set; }    public string Phone { get; set; }    public string Country { get; set; }}

以上例子中 无声明显示方式和显式声明为XML 方式的输出结果:


  <?xml version="1.0" encoding="utf-8" ?>
<ArrayOfEmployee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<Employee>
  <Name>Ajay Singh</Name>
  <Company>Birlasoft Ltd.</Company>
  <Address>LosAngeles California</Address>
  <Phone>310-235-1535</Phone>
  <Country>US</Country>
  </Employee>
<Employee>
  <Name>Ajay Singh</Name>
  <Company>Birlasoft Ltd.</Company>
  <Address>D-195 Sector Noida</Address>
  <Phone>1204675</Phone>
  <Country>India</Country>
  </Employee>
  </ArrayOfEmployee>




原创粉丝点击