jQuery Ajax 調用Aspx.Net WebService

來源:互聯網
上載者:User

我在這裡將jQuery Ajax 調用Aspx.Net WebService 的幾個常用的方法做了一個整理,提供給正在找這方面內容的博友,希望能給學習jQuery的朋友一點協助,可以直接複製代碼運行。

 

ws.aspx 代碼

<!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(" | "));
                        });

                    }
                });
            });
        });==============
var aArray = [“sdf”,”dasd”,”dsa”]; //數組$.each(aArray,function(iNum,value){       document.write(“序號:”+iNum+” 值:”+value);});var oObj = {one:1,two:2,three:3};$.each(aArray,function(property,value){       document.write(“屬性:”+ property +” 值:”+value);});==============================================
        //返回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>
WebService1.asmx.cs

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; }
    }
}

本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/shuilv2000/archive/2009/11/24/4863977.aspx

 

JQuery 中的Ajax調用WebServices 的總結 收藏
使用JQuery中javascript:;" onClick="javascript:tagshow(event, 'ajax');" target="_self">ajax方法訪問web服務。

1.ajax方法需要填寫:
 

JScript. code
$.ajax({type:"POST",//註明 返回JsoncontentType:"application/json;utf-8",//CollegeDepartWebServices.asmx web服務名 /GetCollegeDepart 方法名http://www.cnblogs.com/tangself/admin/%22CollegeDepartWebServices.asmx/GetCollegeDepart%22,//strDepartId 參數名稱 collegeId 參數值data:"{strDepartId:"+collegeId+"}",dataType:"json",success:function(result){varjson=nulltry{if(result){//因為返回的是ArrayList 所以迴圈取出其中的值$.each(result,function(i, n){//ddlDepart 為下來菜單。迴圈的向下拉式功能表中添加新的選項ddlDepart.options[ddlDepart.length]=newOption(n.CollegeDepartTitle,n.CollegeDepartId);});}}catch(e){alert("錯誤>>"+e.message);return;}},error:function(data){alert(data.status+">>>"+data.statusText);}});

----
CollegeDepartWebServices.asmx.cs web服務類

C# code
[WebService(Namespace="http://tempuri.org/%22)][WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)][ScriptService]publicclassCollegeDepartWebServices : System.Web.Services.WebService{publicCollegeDepartWebServices(){//如果使用設計的組件,請取消注釋以下行//InitializeComponent();}[WebMethod][System.Xml.Serialization.XmlInclude(typeof(CollegeDepartInfo))]publicArrayList  GetCollegeDepart(stringstrDepartId){CollegeDepartBL.FlushCollegeDepartCache();if(string.IsNullOrEmpty(strDepartId))returnnull;ArrayList myList=CollegeDepartBL.GetCollegeDepartListByCollegeID(int.Parse(strDepartId));returnmyList;}}

說明:
ArrayList 中 存為對象CollegeDepartInfo
其屬性為:stirng CollegeDepartTitle 和 int CollegeDepartId
在javascript中
ddlDepart.options[ddlDepart.length]=new Option(n.CollegeDepartTitle,n.CollegeDepartId);

Option的參數就是依據他們的。

最後重要的是:
類上方添加的
[ScriptService]
必須添加,否則ajax無法調用WebService

 

本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/shuilv2000/archive/2009/02/20/3914822.aspx

 

 

 

$.ajax(properties)
使用HTTP請求(XMLHttpRequest)載入一個遠程頁面。 這是jQuery的低級AJAX實現。要查看進階抽象,見$.set、$.post等。 $.ajax()返回建立好的XMLHttpRequest對象。多數情況下並不需要直接操縱這個對象,但是如果需要手動中止請求,它也是可用的。 注意:要確保伺服器返回正確的MIME類型(例如:XML是“text/xml”)。如果返回了錯誤的MIME類型就會導致jQuery無法處理的嚴重問題。

支援的資料類型包括(見dataType選項):

 "xml": 返回一個可以由jQuery對象處理的XML文檔。

"html": 返回純文字格式的HTML,包括求值後的指令碼標記。

"script": 將響應作為Javascript語句求值,並返回純文字。

"json": 將響應作為JSON求值,並返回一個Javascript對象。

$.ajax()帶有一個參數--“名/值對”形式的一個對象,用於初始化和處理請求。

以下就是可用的所有“名/值對”:

(String) url - 要將請求發送到的URL地址。

(String) type - 請求的類型 ("POST" 或 "GET"), 預設是 "GET"。

(String) dataType - 期望從伺服器端返回的資料類型。無預設值:如果伺服器返回XML,就將responseXML傳遞到回呼函數,否則將resposeText傳遞到回呼函數。

 (Boolean) ifModified - 只有響應自上次請求後被修改過才承認是成功的請求。是通過檢查頭部的Last-Modified值實現的。預設值為false,即忽略

對部分的檢查 (Number) timeout - 覆蓋全域延遲的局部延遲,例如,在其他所有延遲經過1秒鐘後,啟動一個較長延遲的單獨請求。有關全域延遲,見$.ajaxTimeout()。

 (Boolean) global - 是否為當前的請求觸發全域AJAX事件處理函數,預設值為true。設定為false可以防止觸發像ajaxStart或ajaxStop這樣的全域事件處理函數。

 (Function) error - 當請求失敗時調用的函數。這個函數會得到三個參數:XMLHttpRequest對象、一個描述所發生的錯誤類型的字串和一個可選異常對象(如果有)。

 (Function) success - 當請求成功時調用的函數。這個函數會得到一個參數:從伺服器返回的資料(根據“dataType”進行了格式化)。 (Function) complete - 當請求完成時調用的函數。這個函數會得到兩個參數:XMLHttpRequest對象和一個描述請求成功的類型的字串。

 (Object|String) data - 要發送到伺服器的資料。如果還不是一個字串,就自動輪換為一個查詢字串。即附加到GET請求的url後面的字串。要防止自動處理見processData選項。

 (String) contentType - 設定發送請求的content=type。預設值是 "application/x-www-form-urlencoded", 這個值能滿足多數情況。

 (Boolean) processData - 在預設的情況下,如果data選項傳進的資料是一個對象而不是字串,將會自動地被處理和轉換成一個查詢字串,以適應預設的content-type--"application/x-www-form-urlencoded"。如果想發送DOMDocuments,就要把這個選項設定為false。

 (Boolean) async - 在預設的情況下,所有請求都是以非同步方式發送的(值為true)。如果要使用同步方式,需要將此項設定為false。 (Function) beforeSend - 用於設定自訂頭部等資訊的預調用函數,接收一個唯一的參數--XMLHttpRequest對象。

Load a remote page using an HTTP request. This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions. $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't need that object to manipulate directly, but it is available if you need to abort the request manually. Note: Make sure the server sends the right mimetype (eg. xml as "text/xml"). Sending the wrong mimetype will get you into serious trouble that jQuery can't solve. Supported datatypes are (see dataType option): "xml": Returns a XML document that can be processed via jQuery. "html": Returns HTML as plain text, included script tags are evaluated. "script": Evaluates the response as Javascript and returns it as plain text. "json": Evaluates the response as JSON and returns a Javascript Object $.ajax() takes one argument, an object of key/value pairs, that are used to initalize and handle the request. These are all the key/values that can be used: (String) url - The URL to request. (String) type - The type of request to make ("POST" or "GET"), default is "GET". (String) dataType - The type of data that you're expecting back from the server. No default: If the server sends xml, the responseXML, otherwise the responseText is passed to the success callback. (Boolean) ifModified - Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. (Number) timeout - Local timeout to override global timeout, eg. to give a single request a longer timeout while all others timeout after 1 second. See $.ajaxTimeout() for global timeouts. (Boolean) global - Whether to trigger global AJAX event handlers for this request, default is true. Set to false to prevent that global handlers like ajaxStart or ajaxStop are triggered. (Function) error - A function to be called if the request fails. The function gets passed tree arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occured. (Function) success - A function to be called if the request succeeds. The function gets passed one argument: The data returned from the server, formatted according to the 'dataType' parameter. (Function) complete - A function to be called when the request finishes. The function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request. (Object|String) data - Data to be sent to the server. Converted to a query string, if not already a string. Is appended to the url for GET-requests. See processData option to prevent this automatic processing. (String) contentType - When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases. (Boolean) processData - By default, data passed in to the data option as an object other as string will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send DOMDocuments, set this option to false. (Boolean) async - By default, all requests are send asynchronous (set to true). If you need synchronous requests, set this option to false. (Function) beforeSend - A pre-callback to set custom headers etc., the XMLHttpRequest is passed as the only argument.

傳回值
XMLHttpRequest

參數
properties (Map): Key/value pairs to initialize the request with.
樣本
說明:
載入並執行一個JavaScript檔案。

jQuery 代碼:
$.ajax({ type: "GET", url: "test.js", dataType: "script" })
 
--------------------------------------------------------------------------------

說明:
將資料儲存到伺服器,並在儲存完成後通報使用者。

jQuery 代碼:
$.ajax({ type: "POST", url: "some.php", data: "name=John&location=Boston", success: function(msg){ alert( "Data Saved: " + msg ); } });
 
--------------------------------------------------------------------------------

說明:
同步載入資料。當請求處於活動期間阻塞瀏覽器。如果必須同步載入資料,最好是通過其他手段來阻止使用者的互動,而不是阻塞整個瀏覽器。

jQuery 代碼:
var html = $.ajax({ url: "some.php", async: false }).responseText;
 
--------------------------------------------------------------------------------

說明:
將一個XML文檔作為資料發送到伺服器。通過將processData選項設定為false,可以避免把自動把資料轉換為字串。

jQuery 代碼:
var xmlDocument = [create xml document]; $.ajax({ url: "page.php", processData: false, data: xmlDocument, success: handleResponse });

本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/shuilv2000/archive/2009/11/24/4860787.aspx

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.