2012年11月9日 星期五

{C#} ajax call WebMethod &ashx 應用

一、WebMethod :
aspx:
var strURL = 'WebForm2.aspx/GetValue';
                $.ajax({
                    type: 'POST',
                    url: strURL,
                    data: "{'orderNo':'" + value + "'}",//傳入參數
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    error: function (xhr, ajaxOptions, thrownError) {
                    alert('Ajax request 發生錯誤 ' + xhr.responseText);
                    },
                    success: function (html) {
                        var dataArr = JSON.parse(html.d);
                    }

WebForm2.aspx.cs:
 [WebMethod]
        public static string GetValue(string orderNo)
        {
            object temp = new object();
            temp = DateTime.Now.ToString("yyyy");
            var data = new JavaScriptSerializer().Serialize(temp);
            return data;
        }


二、ashx 應用

aspx:
  var value = $('#<%=txtOrderNo.ClientID %>').val();
                var customer = $('#<%=lblCustomerNo.ClientID %>').text();
                var strURL = 'OrderDetailSource.ashx';
                $.ajax({
                    type: 'GET',
                    url: strURL,
                    data: { orderNo: value, customerId: customer },
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                     error: function (xhr, ajaxOptions, thrownError) {
                    alert('Ajax request 發生錯誤 ' + xhr.responseText);
                    },
                    success: function (result) {
                      //result 直接就是一個json
         alert(result[0].屬性);
                    }});


OrderDetailSource.ashx:
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        //傳入的參數
        string orderNo = context.Request.QueryString["orderNo"] ?? string.Empty;
        string customerId = context.Request.QueryString["customerId"] ?? string.Empty;

        //service 2.0 寫法
        var result = new Service.Operator().abc(orderNo, customerId);
        var temp = JsonConvert.SerializeObject(result, Formatting.Indented);
        //回傳一個json格式資料
        context.Response.Write(temp);
    }

註:
當用方法二時,type要為GET,因為有傳入參數,用Post會直接跑error


參考資料:
http://www.dotblogs.com.tw/threeday0905/archive/2011/01/07/20648.aspx
http://zh-tw.yescript.com/JavascriptScripts-67-.ajaxFanHuiDeJSONWuF/
http://blog.sina.com.cn/s/blog_5ee49d5a0100ss13.html
xhr error message 屬性方法
http://kevyu.blogspot.tw/2010/06/ajaxerror-message.html

Jquery ajax 屬性值列表
http://www.w3school.com.cn/jquery/ajax_ajax.asp

//下面這個範例的$.toJSON({ ids : id })試不出來
http://www.dotblogs.com.tw/rx836/archive/2011/05/10/24658.aspx