jQuery如何调用ASP.NET的WebService

今天搞这个WebService的调用方式了,整了一下午怎么也出不来,愁死了。唉,晚上吃完饭回来上网查下才发现需要在WebApp里的Web.config里需要配置(以下第3步),默认不支持post 调用。唉,郁闷,看了很多jQuery如何调用ASP.NETWebService的相关文章,就是没题这个配置。希望写文章的人,把代码贴全了,也希望网上转载别人文章的人别瞎转载了,你到低试验没有啊,不好使也转载,唉。不说了,写下我的步骤吧。

1、建立项目WebServiceWebApp项目,如图所示

 

2Service1.asmx代码为:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Data;

 

namespace WebService1

{

    /// <summary>

    /// Service1 的摘要说明

    /// </summary>

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

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    [System.ComponentModel.ToolboxItem(false)]

    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。

    [System.Web.Script.Services.ScriptService]

    public class Service1 : System.Web.Services.WebService

    {

        //无参方法

        [WebMethod]

        public string HelloWorld()

        {

            return "Hello World";

        }

 

        //有参方法1

        [WebMethod]

        public int Add(int a, int b)

        {

            return a + b;

        }

 

        //有参方法2

        [WebMethod]

        public int Sum(int x)

        {

            int sum = 0;

            for (int i = 0; i <= x; i++)

            {

                sum += i;

            }

            return sum;

        }

 

        // 返回一个复合类型

        [WebMethod]

        public  Student GetStudentByStuNo(string stuNo)

        {

            if(stuNo=="001")

                return new Student { StuNo = "001", StuName = "张三" };

            if(stuNo=="002")

                return new Student { StuNo = "002", StuName = "李四" };

            return null;

        }

 

        //返回返回泛型集合的

        [WebMethod]

        public List<Student> GetList()

        {

            List<Student> list = new List<Student>();

 

            list.Add(new Student() { StuNo = "001", StuName = "张三" });

            list.Add(new Student() { StuNo = "002", StuName = "李四" });

            list.Add(new Student() { StuNo = "003", StuName = "王五" });

            return list;

        }

 

        //返回DataSet

        [WebMethod]

        public  DataSet GetDataSet()

        {

            DataSet ds = new DataSet();

            DataTable dt = new DataTable();

            dt.Columns.Add("StuNo", Type.GetType("System.String"));

            dt.Columns.Add("StuName", Type.GetType("System.String"));

            DataRow dr = dt.NewRow();

            dr["StuNo"] = "001"; dr["StuName"] = "张三";

            dt.Rows.Add(dr);

 

            dr = dt.NewRow();

            dr["StuNo"] = "002"; dr["StuName"] = "李四";

            dt.Rows.Add(dr);

 

            ds.Tables.Add(dt);

            return ds;

        }

    }

    public class Student

    {

        public string StuNo { get; set; }

        public string StuName { get; set; }

    }

}

3、打开WebApp项目JqueryInvokeWebService里的web.config文件,在system.web节下面加上以下配置

    <webServices >

        <protocols >

            <add name="HttpSoap"/>

            <add name="HttpPost"/>

            <add name="HttpGet"/>

            <add name="Documentation"/>

        </protocols>

    </webServices>

4Default.aspx代码为:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JqueryInvokeWebService._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>

    <script type="text/javascript">

        // 1、调用无参数方法

        $(document).ready(function() {

            $('#Button1').click(function() {

                $.ajax({

                    type: "POST",                           //访问WebService使用Post方式请求

                    contentType: "application/json",        //WebService 会返回Json类型

                    url: "http://localhost:3152/Service1.asmx/HelloWorld",   //调用WebService的地址和方法名称组合---WsURL/方法名

                    data: "{}",                             //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到      

                    dataType: 'json',

                    success: function(result) {             //回调函数,result,返回值

 

                        alert(result.d);

                    }

                });

            });

        });

 

        //2、调用带参数的方法

        $(document).ready(function() {

            $('#Button2').click(function() {

                $.ajax({

                    type: "POST",                       //访问WebService使用Post方式请求

                    contentType: "application/json",    //WebService 会返回Json类型

                    url: "http://localhost:3152/Service1.asmx/Add", //调用WebService的地址和方法名称组合---WsURL/方法名

                    data: "{a:3,b:4}",                  //注意参数名字要和WebService里的Add方法里参数名字一致,否则不得行

                    dataType: 'json',

                    success: function(result) {         //回调函数,result,返回值

 

                        alert(result.d);

                    }

                });

            });

        });

 

        //3、调用复合类型的方法      

         $(document).ready(function() {

            $('#Button3').click(function() {

                $.ajax({

                    type: "POST",                       //访问WebService使用Post方式请求

                    contentType: "application/json",    //WebService 会返回Json类型

                    url: "http://localhost:3152/Service1.asmx/GetStudentByStuNo", //调用WebService的地址和方法名称组合---WsURL/方法名

                    data: "{stuNo:'002'}",

                    dataType: 'json',

                    success: function(result) {         //回调函数,result,返回值

                        alert("学号:"+result.d["StuNo"] + ",姓名:" + result.d["StuName"]);

                    }

                });

              });

          });

 

          //4、调用返回泛型集合的方法

         $(document).ready(function() {

            $('#Button4').click(function() {

                $.ajax({

                    type: "POST",                       //访问WebService使用Post方式请求

                    contentType: "application/json",    //WebService 会返回Json类型

                    url: "http://localhost:3152/Service1.asmx/GetList", //调用WebService的地址和方法名称组合---WsURL/方法名

                    data: "{}",

                    dataType: 'json',

                    success: function(result) {         //回调函数,result,返回值

                        $(result.d).each(function() {

                             $("#lbResult").append(this["StuNo"] + "," + this["StuName"] + "<br />");

                        });                   

                     }

                 });

              });

          });

 

          // 5、调用返回DataSet(xml格式)的方法

          $(document).ready(function() {

              $('#Button5').click(function() {

                  $.ajax({

                      type: "POST",                     //访问WebService使用Post方式请求

                      url: "http://localhost:3152/Service1.asmx/GetDataSet", //调用WebService的地址和方法名称组合---WsURL/方法名

                      data: "{}",

                      dataType: "xml",                  //返回XML数据类型

                      success: function(result) {       //回调函数,result,返回值

                          $(result).find("Table1").each(function() {

                              alert("学号:" + $(this).find("StuNo").text() + ",姓名:" + $(this).find("StuName").text());

                              $('#lbResult').append($(this).find("StuNo").text() + " " + $(this).find("StuName").text() + "<br />");

                          });

                      }

                  });

              });

          });

 

          //显示动画效果

          $(document).ready(function() {

              $('#loading').ajaxStart(function() {

                  $(this).show();

              }).ajaxStop(function() {

                  $(this).hide();

              });

 

          });

 

    </script>

 

</head>

<body>

    <form id="form1" runat="server">

    <div>

 

        <input id="Button1" type="button" value="调用无参数方法" /><br />

        <input id="Button2" type="button" value="调用带参数方法" /><br />

        <input id="Button3" type="button" value="调用复合类型的方法" /><br />

        <input id="Button4" type="button" value="调用返回泛型集合的方法" /><br />

        <input id="Button5" type="button" value="调用返回DataSet的方法" /><br />

        <img id="loading" style="display: none;" alt="loading" src="loading.gif" /><br />

        <asp:Label ID="lbResult" runat="server" Text=""></asp:Label>

    </div>

    </form>

</body>

</html>

5、其他资源,jquery-1.4.1-vsdoc需要到网上下载,安装VS.NET2010后建立个项目自动就增加了,还有一个图片
没有的话暂时用我的这个图片吧

6、运行效果为:

 

 

 

参考:

http://blog.csdn.net/atian15/archive/2009/02/03/3859499.aspx

http://topic.csdn.net/u/20090805/10/27f4361a-208e-4aef-8f69-6343b7f3a0a2.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值