2012-11-20

[Javascript] jQuery.ajax連結ashx、aspx、web service(asmx)的用法

.ajax透過ashx取得JSON這篇之後,再來簡單記錄一下.ajax要如何透過ashx、aspx、web service(asmx)三種方式來取得後端的資料~

.ashx(泛型處理常式)

此範例中,有引用System.Web.SessionState與實作IReadOnlySessionState,才能在程式碼裡面讀到Session。
ashx:
<%@ WebHandler Language="C#" Class="TestUserInfo" %>

using System;
using System.Web;
using System.Web.SessionState;

public class TestUserInfo : IHttpHandler, IReadOnlySessionState 
{
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string sUserName = context.Request.Form["UserName"];
        string sUserID = context.Session["UserID"].ToString();
        string sUserInfo = string.Format("{0} {1}", sUserID, sUserName);
        context.Response.Write(sUserInfo);
    }
 
    public bool IsReusable {
        get { return false; }
    }
}
Javascript:
$(document).ready(function() {
 $('#txtName').change(function() {
  var UserName = $(this).val();
  $.ajax({
   type: 'post',
   url: "TestUserInfo.ashx",
   data: 'UserName=' + UserName,
   success: function(userInfo) {
    $('#txtResult')[0].value = userInfo;
   },
   error: function() { alert('ajax failed'); }
  })
 });
});

.aspx(一般網頁頁面)

aspx:只保留第一行<%@ Page... %>就好
<%@ Page Language="C#" ... %>
aspx.cs:
using System;

public partial class TestUserInfo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string sUserName = Request.Form["UserName"];
        string sUserID = Session["UserID"].ToString();
        string sUserInfo = string.Format("{0} {1}", UserID, UserName);
        Response.Write(sUserInfo);
    }
}
Javascript:
$(document).ready(function() {
 $('#txtName').change(function() {
  var UserName = $(this).val();
  $.ajax({
   type: 'post',
   url: "TestUserInfo.aspx",
   data: 'UserName=' + UserName,
   success: function(userInfo) {
    $('#txtResult')[0].value = userInfo;
   },
   error: function() { alert('ajax failed'); }
  })
 });
});

.asmx(Web Service)

[System.Web.Script.Services.ScriptService]要取消註解。
method上頭加上[WebMethod(EnableSession=true)],才能使用Session。
asmx:
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//下面這行取消註解。
[System.Web.Script.Services.ScriptService]
public class TestUserInfo : System.Web.Services.WebService
{
    public TestUserInfo () {
        //如果使用設計的元件,請取消註解下行程式碼 
        //InitializeComponent(); 
    }

    [WebMethod(EnableSession=true)]
    public string GetUserInfo(string UserName) 
 {
  string sUserID = Session["UserID"].ToString();
  string sUserInfo = string.Format("{0} {1}", UserID, UserName);
        return sUserInfo;
    }
}
Javascript:要注意的是,雖然return的是string,但是Javascript實際接到的是xml格式的字串。
$(document).ready(function() {
 $('#txtName').change(function() {
  var UserName = $(this).val();
  $.ajax({
   type: 'post',
   url: "TestUserInfo.asmx/GetUserInfo",
   data: 'UserName=' + UserName,
   success: function(oXml) {
    var xmlDoc = oXml;  
    var userInfo = xmlDoc.childNodes(1).firstChild.nodeValue;
    $('#txtResult')[0].value = userInfo;
   },
   error: function() { alert('ajax failed'); }
  })
 });
});


參考來源:In 91

沒有留言:

張貼留言