Jquery调用Webservice传递Json数组

   Jquery由于提供的$.ajax强大方法,使得其调用webservice实现异步变得简单起来,可以在页面上传递Json字符串到Webservice中,Webservice方法进行业务处理后,返回Json对象给页面,让页面去展现。

      这一切都非常的简单,今天要学习的并非这些。我们在实际处理业务过程中,会发现往往页面要传递给webservice 的并非一个或多个字符串,有时候需要传递的是一个组合数据,如这样的一组数据:

  {'Employee': [{'name':'John','sex':'man','age':'25'},{'name':'Tom','sex':'man','age':'21'}]}

客户端将这样的Json字符串作为$.ajax方法的data参数是没有问题的,然而,服务端的webservice该如何去写接收参数却成为了一个问题。在百度、谷歌了一番后,只发现提问的却没有回答的。索性还是自己去研究吧,发现其实Employee对象首先是一个数组,其次数组的每一项都是一个Dictionary<string,string>字典类型。于是我尝试在服务端使用Dictionary<string,string>[] Employee来接收客户端传递的参数,一切如我所料,成功!

客户端代码如下: 

 1 代码
 2 
 3             //JQuery 调用webService导入数据
 4             function LoadData() {
 5                 var studentData = CollectionData();
 6                 $.ajax({
 7                     url: "ImportDataService.asmx/ImportStu",
 8                     type: "post",
 9                     contentType: "application/json;charset=utf-8",
10                     dataType: "json",
11                     data: "{'students':[{'name':'KoBe ','sex':'boy','age':'20'},{'name':'Mary','sex':'girl','age':'19'}]}",
12                     success: function(result) {
13                         alert(result.d);
14                     },
15                     error: function(e) {
16                         alert(e.responseText);
17                     }
18                 });
19             }
View Code

服务端代码如下:

 1 代码
 2 
 3         /// <summary>
 4         /// 
 5         /// </summary>
 6         /// <param name="students"></param>
 7         /// <returns></returns>
 8         [WebMethod]
 9         [ScriptMethod(ResponseFormat=ResponseFormat.Json)]
10         public string ImportStu(Dictionary<string,string> []students)
11         {
12             if (students.Length == 0)
13             {
14                 return "没有任何数据!";
15             }
16             else
17             {
18                 try
19                 {
20                     foreach (Dictionary<string, string> stu in students)
21                     {
22                         //构造一个新的Student对象。
23                         Student student = new Student();
24 
25                         //为新构造的Student对象属性赋值。
26                         foreach (string key in stu.Keys)
27                         {
28                             switch (key)
29                             {
30                                 case "name":
31                                     student.Name = stu[key];
32                                     break;
33                                 case "sex":
34                                     student.Sex = stu[key];
35                                     break;
36                                 case "age":
37                                     int age;
38                                     if (Int32.TryParse(stu[key], out age))
39                                     {
40                                         student.Age = age;
41                                     }
42                                     else
43                                     {
44                                         student.Age = 0;
45                                     }
46                                     break;
47                                 default:
48                                     break;
49                             }
50                         }
51                     }
52                     return "导入学生成功!";
53                 }
54                 catch
55                 {
56                     throw new Exception("导入学生失败!");
57                 }
58             }
59         }
View Code

需要注意的是,服务端参数名需要和客户端Json数组的key值相同,如上代码中,参数名都为students。

以上是转自:http://www.cnblogs.com/RascallySnake/archive/2010/04/08/1707521.html

服务端代码如下:

 1 using System.Web.Script.Services;
 2 using System.Web.Services;
 3 using WebWeatherWarning.Action;
 4 
 5 namespace WebWeatherWarning
 6 {
 7     /// <summary>
 8     /// WeatherService 的摘要说明
 9     /// </summary>
10     [WebService(Namespace = "http://tempuri.org/")]
11     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
12     [System.ComponentModel.ToolboxItem(false)]
13     // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
14      [ScriptService]
15     public class WeatherService : WebService
16     {
17 
18         [WebMethod]
19         [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
20         public string GetWeather()
21         {
22             const string sql = "SELECT * FROM DUAL";
23             var result=WeatherTask.GetInstance().GetWeather(sql);
24             return result != null ? ParseTags(result) : null;
25         }
26         public static string ParseTags(string htmlStr)
27         {
28             return System.Text.RegularExpressions.Regex.Replace(htmlStr, "<[^>]*>", "");
29         }
30     }
View Code

客户端代码如下:

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 5     <title></title>
 6     <script src="Lib/jquery-1.8.2.min.js"></script>
 7     <script>
 8         $(function() {
 9             $("#btnQuery").click(function() {
10                 $.ajax({
11                     type: "GET", //访问WebService使用Post方式请求
12                     contentType: "application/json;charset=utf-8", //WebService 会返回Json类型
13                     url: "/WeatherService.asmx/GetWeather", //调用WebService
14                     data: "{}", //Email参数
15                     dataType: 'json',
16                     beforeSend: function (x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); },
17                     error: function (x, e) { },
18                     success: function (response) { //回调函数,result,返回值
19                         debugger;
20 
21                         var json = eval('(' + response.d + ')');
22                         if (json && json.length > 0) {
23                             $("#content").html(json[0].PCONTENT);
24                         } else {
25                             alert("没有数据!!!");
26                         }
27                     }
28                 });
29 
30             });
31 
32           
33         })
34 
35     </script>
36 </head>
37 
38 <body>
39 <input id="btnQuery" type="button" value="button"/>
40 <div>
41     <p id="content"></p>
42 </div>
43 </body>
44 </html>
View Code

配置文件代码如下:

web.config里需要配置2个地方

<httpHandlers>
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </httpHandlers>
在<system.web></system.web>之间加入
<webServices>
      <protocols>
        <add name="HttpPost" />
        <add name="HttpGet" />
      </protocols>
    </webServices>

 1 <system.web>
 2     <httpHandlers>
 3       <remove verb="*" path="*.asmx"/>
 4       <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
 5     </httpHandlers>
 6     <httpRuntime/>
 7     <webServices>
 8       <protocols>
 9         <add name="HttpPost"/>
10         <add name="HttpGet"/>
11       </protocols>
12     </webServices>
13     <pages controlRenderingCompatibilityVersion="4.0"/>
14     <compilation debug="true"/>
15   </system.web>
View Code
原文地址:https://www.cnblogs.com/zxbzl/p/5824991.html