[memo]使用JQuery AJAX 呼叫 SERVER CODE

摘要:[memo]使用JQuery AJAX 呼叫 SERVER CODE

其實網路上有不少分享JQuery 如何做 Ajax 呼叫 Server 端method方式。

大體上如果要我自己開發,能夠簡單一種開發模式是最好,例如: 如果都用server side 控件開發,那就儘量不要加太多javascript

如果需求實在太RIA了,用Server side 控件不好做,那我寧願該頁面整個都是使用Javascript framework來開發。

我在實務工作上就分這兩類,今天剛看到 91 分享的開發方式,也順便筆記一下自己的開發模式。

主要步驟如下:

  1. 在ASPX頁面移除form標記 ( 這是為了避免不必要的POSTBACK )
  2. JQuery 執行 ajax 所要post 的 url ,其Method 名稱必須要與後端 method 名稱對應 。
  3. 記得Server Side Method 必須為static
  4. 在server side method 上加上[WebMethod] Attribute

View.aspx 程式碼如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="View.aspx.cs" Inherits="View" %>

<!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">
<script src="Scripts/jquery-1.5.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function Search() {
            $.ajax({
                type: "POST",
                url: "View.aspx/Search",
                contentType: "application/json; charset=utf-8",
                data: "{}",
                dataType: "json",
                success: function (data) {
                    alert(data.d);
                }                
            });
        }
    </script>
    <title></title>
</head>
<body>
   <div>
        <button id="btnSearch" onclick="Search()">
            查詢</button>
    </div>    
</body>
</html>

View.aspx.cs 程式碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

public partial class View : System.Web.UI.Page
{

    [WebMethod(EnableSession = true)]
    public static string Search()
    {
        return "Hello JQuery";
    }
}