jquery ajax調用webservice

 jquery部分:javascript

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ws.aspx.cs" Inherits="jQuery.Learning.ws" %>

<!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 id="Head1" runat="server">
    <title></title>

    <script src="jquery.js" type="text/javascript"></script>

    <style type="text/css">
        .hover
        {
            cursor: pointer; /*小手*/
            background: #ffc; /*背景*/
        }
        .button
        {
            width: 150px;
            float: left;
            text-align: center;
            margin: 10px;
            padding: 10px;
            border: 1px solid #888;
        }
        #dictionary
        {
            text-align: center;
            font-size: 18px;
            clear: both;
            border-top: 3px solid #888;
        }
        #loading
        {
            border: 1px #000 solid;
            background-color: #eee;
            padding: 20px;
            margin: 100px 0 0 200px;
            position: absolute;
            display: none;
        }
        #switcher
        {
        }
    </style>

    <script type="text/javascript">


        //無參數調用
        $(document).ready(function() {
            $('#btn1').click(function() {
                $.ajax({
                    type: "POST",   //訪問WebService使用Post方式請求
                    contentType: "application/json", //WebService 會返回Json類型
                    url: "WebService1.asmx/HelloWorld", //調用WebService的地址和方法名稱組合 ---- WsURL/方法名
                    data: "{}",         //這裏是要傳遞的參數,格式爲 data: "{paraName:paraValue}",下面將會看到       
                    dataType: 'json',
                    success: function(result) {     //回調函數,result,返回值
                        $('#dictionary').append(result.d);
                    }
                });
            });
        });


        //有參數調用
        $(document).ready(function() {
            $("#btn2").click(function() {
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "WebService1.asmx/GetWish",
                    data: "{value1:'心想事成',value2:'萬事如意',value3:'牛牛牛',value4:2009}",
                    dataType: 'json',
                    success: function(result) {
                        $('#dictionary').append(result.d);
                    }
                });
            });
        });
        
        
        //返回集合(引用自網絡,很說明問題)
        $(document).ready(function() {
            $("#btn3").click(function() {
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "WebService1.asmx/GetArray",
                    data: "{i:10}",
                    dataType: 'json',
                    success: function(result) {
                        $(result.d).each(function() {
                            //alert(this);
                            $('#dictionary').append(this.toString() + " ");
                            //alert(result.d.join(" | "));
                        });
                    }
                });
            });
        });


        //返回複合類型
        $(document).ready(function() {
            $('#btn4').click(function() {
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "WebService1.asmx/GetClass",
                    data: "{}",
                    dataType: 'json',
                    success: function(result) {
                        $(result.d).each(function() {
                            //alert(this);
                            $('#dictionary').append(this['ID'] + " " + this['Value']);
                            //alert(result.d.join(" | "));
                        });

                    }
                });
            });
        });

        //返回DataSet(XML)
        $(document).ready(function() {
            $('#btn5').click(function() {
                $.ajax({
                    type: "POST",
                    url: "WebService1.asmx/GetDataSet",
                    data: "{}",
                    dataType: 'xml', //返回的類型爲XML ,和前面的Json,不同了
                    success: function(result) {
                    //演示一下捕獲
                        try {   
                            $(result).find("Table1").each(function() {
                                $('#dictionary').append($(this).find("ID").text() + " " + $(this).find("Value").text());
                            });
                        }
                        catch (e) {
                            alert(e);
                            return;
                        }
                    },
                    error: function(result, status) { //若是沒有上面的捕獲出錯會執行這裏的回調函數
                        if (status == 'error') {
                            alert(status);
                        }
                    }
                });
            });
        });




        //Ajax 爲用戶提供反饋,利用ajaxStart和ajaxStop 方法,演示ajax跟蹤相關事件的回調,他們兩個方法能夠添加給jQuery對象在Ajax先後回調
        //但對與Ajax的監控,自己是全局性的
        $(document).ready(function() {
            $('#loading').ajaxStart(function() {
                $(this).show();
            }).ajaxStop(function() {
                $(this).hide();
            });
        });

        // 鼠標移入移出效果,多個元素的時候,可使用「,」隔開
        $(document).ready(function() {
            $('div.button').hover(function() {
                $(this).addClass('hover');
            }, function() {
                $(this).removeClass('hover');
            });
        });
        
        
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div id="switcher">
        <h2>
            jQuery 的WebServices 調用</h2>
        <div class="button" id="btn1">
            HelloWorld</div>
        <div class="button" id="btn2">
            傳入參數</div>
        <div class="button" id="btn3">
            返回集合</div>
        <div class="button" id="btn4">
            返回複合類型</div>
        <div class="button" id="btn5">
            返回DataSet(XML)</div>
    </div>
    <div id="loading">
        服務器處理中,請稍後。
    </div>
    <div id="dictionary">
    </div>
    </form>
</body>
</html>

 webservice部分:css

 

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data; namespace jQuery.Learning {     /// <summary>     /// WebService1 的摘要說明     /// </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 WebService1 : System.Web.Services.WebService     {         /// <summary>         /// 無參數         /// </summary>         /// <returns></returns>         [WebMethod]         public string HelloWorld()         {             return "Hello World ";         }         /// <summary>         /// 帶參數         /// </summary>         /// <param name="value1"></param>         /// <param name="value2"></param>         /// <param name="value3"></param>         /// <param name="value4"></param>         /// <returns></returns>         [WebMethod]         public string GetWish(string value1, string value2, string value3, int value4)         {             return string.Format("祝您在{3}年裏 {0}、{1}、{2}", value1, value2, value3, value4);         }         /// <summary>         /// 返回集合         /// </summary>         /// <param name="i"></param>         /// <returns></returns>         [WebMethod]         public List<int> GetArray(int i)         {             List<int> list = new List<int>();             while (i >= 0)             {                 list.Add(i--);             }             return list;         }         /// <summary>         /// 返回一個複合類型         /// </summary>         /// <returns></returns>         [WebMethod]         public Class1 GetClass()         {             return new Class1 { ID = "1", Value = "牛年大吉" };         }         /// <summary>         /// 返回XML         /// </summary>         /// <returns></returns>         [WebMethod]         public DataSet GetDataSet()         {             DataSet ds = new DataSet();             DataTable dt = new DataTable();             dt.Columns.Add("ID", Type.GetType("System.String"));             dt.Columns.Add("Value", Type.GetType("System.String"));             DataRow dr = dt.NewRow();             dr["ID"] = "1";             dr["Value"] = "新年快樂";             dt.Rows.Add(dr);             dr = dt.NewRow();             dr["ID"] = "2";             dr["Value"] = "萬事如意";             dt.Rows.Add(dr);             ds.Tables.Add(dt);             return ds;         }     }     //自定義的類,只有兩個屬性     public class Class1     {         public string ID { get; set; }         public string Value { get; set; }     } }
相關文章
相關標籤/搜索