[jQuery]jQuery Ajax 呼叫 Web Service 傳遞參數範例

[jQuery]jQuery Ajax 呼叫 Web Service 傳遞參數範例

這東西不常用還真的是容易忘記,所以寫一篇來記錄一下,方便以後要用到的時候可以有個範例參考。

首先寫個測試的Web Service,也特別將這個Web Service放在不同的資料夾中

XXX / ws001.asmx

裡面的內容如下:

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols

' 若要允許使用 ASP.NET AJAX 從指令碼呼叫此 Web 服務,請取消註解下一行。
' <System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class ws001
     Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function HelloWorld() As String
        Return "Hello World"
    End Function

    <WebMethod()> _
    Public Function myTest1(ByVal UsrID As String, ByVal DiscussID As Decimal) As String
        Return "Hi" + UsrID + ",<br />DiscussID:" + DiscussID.ToString + "<br/>" + Now.ToString()

    End Function

End Class

接著在測試畫面中,安排一個按鈕稱為btn1

<input id="btn1" type="button" value="XXX" />

然後撰寫按下按鈕後,透過jQuery ajax去存取Web Service

    <script type="text/javascript">
        $(document).ready(function () {

            $('#btn1').click(function () {
                alert('xx');

                var strURL = 'XXX/ws001.asmx/myTest1';
                //var strURL = 'XXX/ws001.asmx/HelloWorld';
                $.ajax({
                    type: 'POST',
                    url: strURL,
                    dataType: 'xml',
                    data: { UsrID: "topcat", DiscussID: "3" },
                    success: function (oXml) {
                        alert($('string', oXml).text());
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(xhr.status);
                        alert(thrownError);
                    }
                });
            });

        })
    </script>

注意一下data傳遞參數的寫法,網路上有很多種,目前這一種測試OK的。

data: { UsrID: "topcat", DiscussID: "3" },

 


以下是簽名:


Microsoft MVP
Visual Studio and Development Technologies
(2005~2019/6) 
topcat
Blog:http://www.dotblogs.com.tw/topcat