asp.net下使用jquery 的ajax+WebService+json 实现无刷新取后台值的实现

  我在这里将jQuery Ajax 调用Aspx.Net WebService 的几个常用的方法做了一个整理,提供给正在找这方面内容的程序员,希望能给学习jQuery的朋友一点帮助,可以直接复制代码运行。

  运行的效果及页面如下:

 

index.aspx代码:

 

  1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="WebApplication5.index" %>
  2 
  3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4 <html xmlns="http://www.w3.org/1999/xhtml">
  5 <head id="Head1" runat="server">
  6     <title></title>
  7     <script src="jquery-1.7.2.min.js" type="text/javascript"></script>
  8 
  9     <style type="text/css">
 10     .hover
 11     {
 12       cursor: pointer; /*小手*/
 13       background: #ffc; /*背景*/
 14     }
 15     .button
 16     {
 17        150px;
 18       float: left;
 19       text-align: center;
 20       margin: 10px;
 21       padding: 10px;
 22       border: 1px solid #888;
 23     }
 24     #dictionary
 25     {
 26       text-align: center;
 27       font-size: 18px;
 28       clear: both;
 29       border-top: 3px solid #888;
 30     }
 31     #loading
 32     {
 33       border: 1px #000 solid;
 34       background-color: #eee;
 35       padding: 20px;
 36       margin: 100px 0 0 200px;
 37       position: absolute;
 38       display: none;
 39     }
 40     #switcher
 41     {
 42     }
 43   </style>
 44     <script type="text/javascript">
 45               //无参数调用
 46         $(document).ready(function () {
 47             $('#btn1').click(function () {
 48                 $.ajax({
 49                     type: "POST", //访问WebService使用Post方式请求
 50                     contentType: "application/json", //WebService 会返回Json类型
 51                     url: "WebService1.asmx/HelloWorld", //调用WebService的地址和方法名称组合 ---- WsURL/方法名
 52                     data: "{}", //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到   
 53                     dataType: 'json',
 54                     success: function (result) { //回调函数,result,返回值
 55                         $('#dictionary').append(result.d);
 56                     }
 57                 });
 58             });
 59         });
 60         //有参数调用
 61         $(document).ready(function () {
 62             $("#btn2").click(function () {
 63                 $.ajax({
 64                     type: "POST",
 65                     contentType: "application/json",
 66                     url: "WebService1.asmx/GetWish",
 67                     data: "{value1:'心想事成',value2:'万事如意',value3:'牛牛牛',value4:2009}",
 68                     dataType: 'json',
 69                     success: function (result) {
 70                         $('#dictionary').append(result.d);
 71                     }
 72                 });
 73             });
 74         });
 75         //返回集合(引用自网络,很说明问题)
 76         $(document).ready(function () {
 77             $("#btn3").click(function () {
 78                 $.ajax({
 79                     type: "POST",
 80                     contentType: "application/json",
 81                     url: "WebService1.asmx/GetArray",
 82                     data: "{i:10}",
 83                     dataType: 'json',
 84                     success: function (result) {
 85                         $(result.d).each(function () {
 86                             //alert(this);
 87                             $('#dictionary').append(this.toString() + " ");
 88                             //alert(result.d.join(" | "));
 89                         });
 90                     }
 91                 });
 92             });
 93         });
 94         //返回复合类型
 95         $(document).ready(function () {
 96             $('#btn4').click(function () {
 97                 $.ajax({
 98                     type: "POST",
 99                     contentType: "application/json",
100                     url: "WebService1.asmx/GetClass",
101                     data: "{}",
102                     dataType: 'json',
103                     success: function (result) {
104                         $(result.d).each(function () {
105                             //alert(this);
106                             $('#dictionary').append(this['ID'] + " " + this['Value']);
107                             //alert(result.d.join(" | "));
108                         });
109                     }
110                 });
111             });
112         });
113         //返回DataSet(XML)
114         $(document).ready(function () {
115             $('#btn5').click(function () {
116                 $.ajax({
117                     type: "POST",
118                     url: "WebService1.asmx/GetDataSet",
119                     data: "{}",
120                     dataType: 'xml', //返回的类型为XML ,和前面的Json,不一样了
121                     success: function (result) {
122                         //演示一下捕获
123                         try {
124                             $(result).find("Table1").each(function () {
125                                 $('#dictionary').append($(this).find("ID").text() + " " + $(this).find("Value").text());
126                             });
127                         }
128                         catch (e) {
129                             alert(e);
130                             return;
131                         }
132                     },
133                     error: function (result, status) { //如果没有上面的捕获出错会执行这里的回调函数
134                         if (status == 'error') {
135                             alert(status);
136                         }
137                     }
138                 });
139             });
140         });
141         //Ajax 为用户提供反馈,利用ajaxStart和ajaxStop 方法,演示ajax跟踪相关事件的回调,他们两个方法可以添加给jQuery对象在Ajax前后回调
142         //但对与Ajax的监控,本身是全局性的
143         $(document).ready(function () {
144             $('#loading').ajaxStart(function () {
145                 $(this).show();
146             }).ajaxStop(function () {
147                 $(this).hide();
148             });
149         });
150         // 鼠标移入移出效果,多个元素的时候,可以使用“,”隔开
151         $(document).ready(function () {
152             $('div.button').hover(function () {
153                 $(this).addClass('hover');
154             }, function () {
155                 $(this).removeClass('hover');
156             });
157         });
158     
159     
160     </script>
161 </head>
162 <body>
163     <form id="form1" runat="server">
164     <div id="switcher">
165         <h2>
166             jQuery 的WebServices 调用</h2>
167         <div class="button" id="btn1">
168             HelloWorld</div>
169         <div class="button" id="btn2">
170             传入参数</div>
171         <div class="button" id="btn3">
172             返回集合</div>
173         <div class="button" id="btn4">
174             返回复合类型</div>
175         <div class="button" id="btn5">
176             返回DataSet(XML)</div>
177     </div>
178     <div id="loading">
179         服务器处理中,请稍后。
180     </div>
181     <div id="dictionary">
182     </div>
183     </form>
184 </body>
185 </html>

WebService1.asmx.cs中代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Services;
 6 using System.Data;
 7 
 8 namespace WebApplication5
 9 {
10     /// <summary>
11     /// WebService1 的摘要说明
12     /// </summary>
13     [WebService(Namespace = "http://tempuri.org/")]
14     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
15     [System.ComponentModel.ToolboxItem(false)]
16     // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
17      [System.Web.Script.Services.ScriptService]
18     public class WebService1 : System.Web.Services.WebService
19     {
20 
21         [WebMethod]
22         public string HelloWorld()
23         {
24             return "Hello World";
25         }
26         /// <summary>
27     /// 带参数
28     /// </summary>
29     /// <param name="value1"></param>
30     /// <param name="value2"></param>
31     /// <param name="value3"></param>
32     /// <param name="value4"></param>
33     /// <returns></returns>
34     [WebMethod]
35     public string GetWish(string value1, string value2, string value3, int value4)
36     {
37       return string.Format("祝您在{3}年里 {0}、{1}、{2}", value1, value2, value3, value4);
38     }
39     /// <summary>
40     /// 返回集合
41     /// </summary>
42     /// <param name="i"></param>
43     /// <returns></returns>
44     [WebMethod]
45     public List<int> GetArray(int i)
46     {
47       List<int> list = new List<int>();
48       while (i >= 0)
49       {
50         list.Add(i--);
51       }
52       return list;
53     }
54     /// <summary>
55     /// 返回一个复合类型
56     /// </summary>
57     /// <returns></returns>
58     [WebMethod]
59     public Class1 GetClass()
60     {
61       return new Class1 { ID = "1", Value = "牛年大吉" };
62     }
63     /// <summary>
64     /// 返回XML
65     /// </summary>
66     /// <returns></returns>
67     [WebMethod]
68     public DataSet GetDataSet()
69     {
70       DataSet ds = new DataSet();
71       DataTable dt = new DataTable();
72       dt.Columns.Add("ID", Type.GetType("System.String"));
73       dt.Columns.Add("Value", Type.GetType("System.String"));
74       DataRow dr = dt.NewRow();
75       dr["ID"] = "1";
76       dr["Value"] = "新年快乐";
77       dt.Rows.Add(dr);
78       dr = dt.NewRow();
79       dr["ID"] = "2";
80       dr["Value"] = "万事如意";
81       dt.Rows.Add(dr);
82       ds.Tables.Add(dt);
83       return ds;
84     }
85   }
86   //自定义的类,只有两个属性
87   public class Class1
88   {
89     public string ID { get; set; }
90     public string Value { get; set; }
91   }
92     }

 

原文地址:https://www.cnblogs.com/dyhdream/p/3096401.html