[jQuery+ASP.NET]jQuery ajax Call webmethod

  • 5289
  • 0
  • 2015-11-06

摘要:[jQuery]Ajax Call webmethod

只需要用到jQuery, 這裡示範Web Form的用法, MVC....有空再測

javascript端

function MyAjaxCall() {
            var resultConfirm = true;
            $.ajax({
                type: "post",
                url: "wFrmFinData.aspx/MyAjaxFunction",
                //不用傳參數的話,放個大括弧就好
                //data: "{}",
                data: '{txtContent: "' + $("input[id*=txtTest]").val() + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,//最後要return或是等等需要用到result的value的話,必須設定為false(就會變成同步執行),不然就不設定,預設是true
                cache:false, //防止ie8一直取到舊資料的話,請設定為false
                success: function (result) {
                    //callback function result(on success)
                    //alert(result.d);
                     resultConfirm = confirm(result.d);//不可以在這邊直接下return,會無效
                },
                failure: function (response) {
                    //callback function result(on failure)
                    alert(response.d);
                }
            });

            //防止按鈕postback,可自行決定是否需要
            //return false;
            return resultConfirm
        }

html

<asp:TextBox ID="txtTest" runat="server" Text="MyTestName"></asp:TextBox>
                                                <asp:Button ID="btnTest" runat="server" Text="AjaxTest" OnClientClick="return MyAjaxCall()" />

 

VB:

  _
    Public Shared Function MyAjaxFunction(ByVal txtContent As String) As String
        Return "Ajax callSuccess!! and get your name:" & txtContent
    End Function

 

C#:(只有測VB, 這是用VB To C# http://www.developerfusion.com/tools/convert/vb-to-csharp/自動轉換的)

[System.Web.Services.WebMethod(EnableSession = true)]
public static string MyAjaxFunction(string txtContent)
{
	return "Ajax callSuccess!! and get your name:" + txtContent;
}

ps.通常回到後端取得資料是取得JSon,所以下篇文章通常會一併參考到

[jQuery+Ajax+Json]如何把DataTable轉成JSon(搭配JSon.net的dll)

ps. par2:如果success裡面的程式碼太多,通常程式設計師會想把ajax程式碼獨立出來到另外一個function

這時候,success還有failure就不要寫在ajax裡面,如下:

function AjaxGetDistrict() {
            return $.ajax({
                type: "post",
                url: "ProgramName.aspx/AjaxGetDistrict",
                //不用傳參數的話,放個大括弧就好
                //data: "{}",
                data: '{districtName: "' + '北區' + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });
        }

然後引用這個Ajax function的時候,就要改用promise的的done事件

var promise = AjaxGetDistrict();
promise.done(function (result) {
    //任何程式碼
});

參考資料:

Calling ASP.Net WebMethod using jQuery AJAX