跳到主要內容

$.ajax透過 WebService 讀取資料範例

常會使用 $.ajax 透過 WebService 取得資料顯示於畫面,寫個簡單範例記錄下來:
結果要得到 "Name1" 的字串顯示於  <div id="bannerId1"></div> 裡面。

JQuery:
var index = 0;
var $res;
 $.ajax({
                type: "POST",
                url: "AAA.aspx/WebServiceFunction",
                data: "{}",   // <-- 不帶參數
                contentType: "application/json; charset=utf-8",
                async: false,    // <-- 使用非同步
                cache: false,    // <--不用 cache  每次重要
                dataType: "json",  // <-- 使用 JSON 格式
                success: function (data) {
                   
                    if (data.hasOwnProperty("d")) {
                        $res = data.d;
                    }
                    else {
                        $res = data;
                    }
                                     
                   var myE1=angular.element(document.querySelector('#bannerId1')); // #bannerId1 是 div 的 ID
                    myE1.append( $res[index].headline); // <-- 這裡會得到 "Name1" 才對
                },
                failure: function (msg) {
                    alert('Error');
                }
            });

C#:
        public class NewsItem
        {
             public string headline { get; set; }
        }
...
        [System.Web.Services.WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static NewsItem[] WebServiceFunction( )
        {
            string strHead = string.Empty;

            List<NewsItem> ItemCollect = new List<NewsItem>( );

            ItemCollect.Add(new NewsItem { headline = "Name1" });              
            ItemCollect.Add(new NewsItem { headline = "Name2" });              
            ItemCollect.Add(new NewsItem { headline = "Name3" });          
            return ItemCollect.ToArray();
        }




留言