jQuery调用ASP.NET的WebService

经常需要使用客户端脚本调用net的WebService,比较常用的是在ScriptManager脚本管理器的环境下使用回调调用WebService的方法,可是这些必须在aspx的页面中进行,难免有些限制。

   jQuery库是我们比较常用的JavaScript库,入门简单,功能强大,对Ajax的支持比较友好。使用jQuery调用net的WebService也是经常遇到的。现将常见调用类型总结如下:

   1、环境

        jQuery 1.3.2

        .net framework 2.0

        Asp.net ajax 1.0

   2、后台WebService的代码

   

[c-sharp] view plaincopy
  1. using System;  
  2. using System.Collections;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Services;  
  6. using System.Web.Services.Protocols;  
  7. using System.Xml.Linq;  
  8. using System.Text;  
  9. using System.Collections.Generic;  
  10. using System.Data;  
  11.   
  12. /// <summary>  
  13. ///WebService 的摘要说明  
  14. /// </summary>  
  15. [WebService(Namespace = "http://tempuri.org/")]  
  16. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  17. //若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。   
  18. [System.Web.Script.Services.ScriptService]  
  19. public class WebService : System.Web.Services.WebService  
  20. {  
  21.   
  22.     public WebService()  
  23.     {  
  24.   
  25.         //如果使用设计的组件,请取消注释以下行   
  26.         //InitializeComponent();   
  27.     }  
  28.     [WebMethod]  
  29.     public string HelloWorld()  
  30.     {  
  31.         return "Hello World";  
  32.     }  
  33.     [WebMethod]  
  34.     public string HelloWorld(string userName)  
  35.     {  
  36.         StringBuilder sb = new StringBuilder();  
  37.         for (int i = 0; i < 100; i++)  
  38.         {  
  39.             sb.AppendLine("<del>Hello World "+i+"<br /></del>");  
  40.         }  
  41.   
  42.         return sb.ToString();  
  43.     }  
  44.     [WebMethod]  
  45.     public StudentInfo GetClass()  
  46.     {  
  47.         StudentInfo s = new StudentInfo();  
  48.         s.StuName = "Accp 4.0";  
  49.         s.Id = 1;  
  50.         return s;  
  51.     }  
  52.     [WebMethod]  
  53.     public List<StudentInfo> GetList()  
  54.     {  
  55.         return (new StudentInfo()).GetList();  
  56.     }  
  57.     [WebMethod]  
  58.     public DataSet GetDataSet()  
  59.     {  
  60.         return (new StudentInfo()).GetDataSet();  
  61.     }  
  62. }  

   WebService中使用的实体类

   

[c-sharp] view plaincopy
  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Security;  
  7. using System.Web.UI;  
  8. using System.Web.UI.HtmlControls;  
  9. using System.Web.UI.WebControls;  
  10. using System.Web.UI.WebControls.WebParts;  
  11. using System.Xml.Linq;  
  12. using System.Collections.Generic;  
  13.   
  14. /// <summary>  
  15. ///StudentInfo 的摘要说明  
  16. /// </summary>  
  17. public class StudentInfo  
  18. {  
  19.     public StudentInfo()  
  20.     {  
  21.     }  
  22.     private string m_stuName;  
  23.   
  24.     public string StuName  
  25.     {  
  26.         get { return m_stuName; }  
  27.         set { m_stuName = value; }  
  28.     }  
  29.     private int m_id;  
  30.   
  31.     public int Id  
  32.     {  
  33.         get { return m_id; }  
  34.         set { m_id = value; }  
  35.     }  
  36.     public DataSet GetDataSet()  
  37.     {  
  38.         DataSet ds = new DataSet();  
  39.         DataTable dt = new DataTable();  
  40.         dt.Columns.Add("Name");  
  41.         dt.Columns.Add("Id");  
  42.   
  43.         for (int i = 0; i < 55; i++)  
  44.         {  
  45.             DataRow row = dt.NewRow();  
  46.             row["Name"] = "Hello World" + i;  
  47.             row["Id"] = i;  
  48.   
  49.             dt.Rows.Add(row);  
  50.         }  
  51.         ds.Tables.Add(dt);  
  52.   
  53.         return ds;  
  54.     }  
  55.     public List<StudentInfo> GetList()  
  56.     {  
  57.         List<StudentInfo> list = new List<StudentInfo>();  
  58.         for (int i = 0; i < 55; i++)  
  59.         {  
  60.             StudentInfo s = new StudentInfo();  
  61.             s.StuName = "Hello World" + i;  
  62.             s.Id = i;  
  63.   
  64.             list.Add(s);  
  65.         }  
  66.         return list;  
  67.     }  
  68. }  

   3、前台显示页面调用

        这里前台页面使用htm页面来进行测试。

       1、无参数调用

         $(document).ready(function() {
            $('#Button1').click(function() {
                $.ajax({
                    type: "POST",   //访问WebService使用Post方式请求
                    contentType: "application/json", //WebService 会返回Json类型
                    url: "../WebService.asmx/HelloWorld", //调用WebService的地址和方法名称组合---WsURL/方法名
                    data: "{}",         //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到      
                    dataType: 'json',
                    success: function(result) {     //回调函数,result,返回值

                           alert(result.d);
                     }
                });

              });

          });

      2、带参数的调用

        

         $(document).ready(function() {
            $('#Button1').click(function() {
                $.ajax({
                    type: "POST",   //访问WebService使用Post方式请求
                    contentType: "application/json", //WebService 会返回Json类型
                    url: "../WebService.asmx/HelloWorld", //调用WebService的地址和方法名称组合---WsURL/方法名
                    data: "{userName:'alpha'}", 
                    dataType: 'json',
                    success: function(result) {     //回调函数,result,返回值

                           alert(result.d);
                    }
                });

              });

          });

      3、返回复合类型        

         $(document).ready(function() {
            $('#Button1').click(function() {
                $.ajax({
                    type: "POST",   //访问WebService使用Post方式请求
                    contentType: "application/json", //WebService 会返回Json类型
                    url: "../WebService.asmx/GetClass", //调用WebService的地址和方法名称组合---WsURL/方法名
                    data: "{}",
                    dataType: 'json',
                    success: function(result) {     //回调函数,result,返回值

                           alert(result.d["StuName"]);
                    }
                });

              });

          });

      4、返回泛型集合        

         $(document).ready(function() {
            $('#Button1').click(function() {
                $.ajax({
                    type: "POST",   //访问WebService使用Post方式请求
                    contentType: "application/json", //WebService 会返回Json类型
                    url: "../WebService.asmx/GetList", //调用WebService的地址和方法名称组合---WsURL/方法名
                    data: "{}",
                    dataType: 'json',
                    success: function(result) {     //回调函数,result,返回值

                           $(result.d).each(function(){
                                $("#result").append(this["Id"]+" "+this["StuName"]+"<br />");
                            });                   

                     }
                 });

              });

          });

      5、返回DataSet(xml格式)

         $(document).ready(function() {
            $('#Button1').click(function() {
                $.ajax({
                    type: "POST",   //访问WebService使用Post方式请求
                    url: "../WebService.asmx/GetDataSet", //调用WebService的地址和方法名称组合---WsURL/方法名
                    data: "{}",
                    dataType: "xml",
                    success: function(result) {     //回调函数,result,返回值

                            $(result).find("Table1").each(function() {
                                $('#result').append($(this).find("Id").text() + " " + $(this).find("Name").text()+"<br />");
                            });               

                     }
                 });

              });

          });

     

      显示动画效果

      $(document).ready(function(){

            $('#loading').ajaxStart(function() {
                $(this).show();
            }).ajaxStop(function() {
                $(this).hide();
            });

      });

  

      HTML代码部分

     <input id="Button1" type="button" value="Invoke" />
     <div id="result">
        <img id="loading" style="display: none;" alt="loading" src="../images/loading.gif" />
     </div>

原文地址:https://www.cnblogs.com/wahaccp/p/4377229.html