jQuery Ajax 仿AjaxPro.Utility.RegisterTypeForAjax輔助方法
更新時間:2011年09月27日 23:48:52 作者:
我們都知道在AjaxPro的方法AjaxPro.Utility.RegisterTypeForAjax(typeof(所在類的類名));會將標(biāo)記有[Ajax.AjaxMethod]方法注冊在客戶端。
在某項目中,設(shè)計模板字段引擎,采用html+jquery實現(xiàn),這里的數(shù)據(jù)就難免需要ajax獲取,但是團隊對于js掌握不一,所以我寫了下面輔助類,可以像ajaxpro一樣簡化ajax的開發(fā)。
代碼-jQueryInvokeMethodAttribute (此處只做標(biāo)示方法處理,所以為空):
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false,Inherited=false)]
public class jQueryInvokeMethodAttribute : Attribute
{
}
代碼-jQueryAjaxUtility(分注冊腳本和調(diào)用ajax事件):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Green.Utility
{
public class jQueryAjaxUtility
{
public static string AjaxInvokeParam = "AjaxInvoke";
public static string AjaxInvokeValue = "1";
public static string ResponseCharset = "UTF-8";
protected static System.Web.UI.Page Page
{
get
{
return System.Web.HttpContext.Current.Handler as System.Web.UI.Page;
}
}
public static void RegisterClientAjaxScript(Type type)
{
if (Page != null)
{
if (System.Web.HttpContext.Current.Request[AjaxInvokeParam] == AjaxInvokeValue)
{
RegisterAjaxInvokeEvent(type);
}
else
{
RegisterAjaxInvokeScript(type);
}
}
}
protected static void RegisterAjaxInvokeScript(Type type)
{
Page.ClientScript.RegisterClientScriptBlock(type.GetType(), type.GetType().FullName + "_" + typeof(jQueryAjaxUtility).FullName + "_AjaxInvokeDefaultOption", "window.defaultAjaxOption={type:'GET',cache:false, dataType:'text'};", true);
if (!jQueryUtilityCache.Current.Exists(type))
{
var methodinfo = type.GetMethods(System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public).Where(t =>
{
var attrs = t.GetCustomAttributes(typeof(jQueryInvokeMethodAttribute), false);
if (attrs != null && attrs.Length > 0)
return true;
return false;
}).ToList();
if (methodinfo != null && methodinfo.Count > 0)
{
System.Text.StringBuilder sb = new StringBuilder();
sb.AppendFormat(" window.{0}=function(){{}}; ", type.Name);
methodinfo.ForEach(t =>
{
var parameters = t.GetParameters().Select(p => p.Name).ToArray();
sb.AppendFormat(" {2}.{0} = function ({1} ajaxOption) {{", t.Name, parameters.Count() > 0 ? string.Join(",", parameters) + "," : "", type.Name);
sb.Append("if(ajaxOption==null||typeof ajaxOption=='undefined'){ajaxOption={};};");
var url = Page.Request.RawUrl.IndexOf("?") == -1 ? Page.Request.RawUrl : Page.Request.RawUrl.Substring(0, Page.Request.RawUrl.IndexOf("?") );
sb.AppendFormat("ajaxOption.url = '{0}';", url);
var data = "''";
if (parameters.Count() > 0)
{
data = (string.Join(" ", parameters.Select(p => string.Format("'&{0}=' + {0}+", p)).ToArray()));
data= data.TrimEnd('+');
}
sb.AppendFormat("ajaxOption.data = 'method={1}&rn={4}&{2}={3}'+{0};", data, t.Name, AjaxInvokeParam, AjaxInvokeValue,Guid.NewGuid().ToString());
sb.Append("ajaxOption= jQuery.extend(window.defaultAjaxOption,ajaxOption);");
sb.Append("jQuery.ajax(ajaxOption);};");
});
jQueryUtilityCache.Current.AddScript(type, sb.ToString());
}
}
var script = jQueryUtilityCache.Current.GetScript(type);
Page.ClientScript.RegisterClientScriptBlock(type.GetType(), type.GetType().FullName + "_" + typeof(jQueryAjaxUtility).FullName + "_AjaxInvoke", script, true);
}
protected string GenertorScript(Type type)
{
return string.Empty;
}
protected static void RegisterAjaxInvokeEvent(Type type)
{
var Request = System.Web.HttpContext.Current.Request;
var Response = System.Web.HttpContext.Current.Response;
var method = Request["method"];
if (string.IsNullOrEmpty(method))
return;
Response.Clear();
var methodinfo = type.GetMethod(method, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
if (methodinfo != null)
{
Response.Charset = ResponseCharset;
Response.ContentType = string.Join(",", Request.AcceptTypes);
var param = methodinfo.GetParameters();
object[] objs = new object[param.Length];
var i = 0;
param.ToList().ForEach(t =>
{
objs[i++] = Convert.ChangeType(Request[t.Name], t.ParameterType);
});
var obj = methodinfo.Invoke(null, objs);
if (obj != null)
{
//序列化
if (!obj.GetType().IsValueType && obj.GetType() != typeof(string))
{
if (Request.AcceptTypes.Contains("text/xml"))
{
Response.Write(Green.Utility.SerializerUtility.XmlSerializer(obj));
}
else if (Request.AcceptTypes.Contains("application/json"))
{
Response.ContentType = "application/json, text/javascript, */*";
Response.Write(Green.Utility.SerializerUtility.JsonSerializer(obj));
}
else
{
Response.Write(obj);
}
}
else
{
Response.Write(obj);
}
}
Response.Flush();
Response.Close();
Response.End();
}
}
}
}
為了考慮反射的性能,加入了類級注冊腳本方法緩存處理jQueryUtilityCache,具體見demo。
測試:
html:
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="button" />
</div>
</form>
后臺方法注冊Page_Load
Green.Utility.jQueryAjaxUtility.RegisterClientAjaxScript(typeof(_Default));
1:
前臺:
_Default.Test("ajax",
{
success: function(e) {
alert(e);
},
dataType: "text"
});
后臺:
[Green.Utility.jQueryInvokeMethod()]
public static string Test(string str)
{
return "hello:" + str;
}
_Default.TestArrayJson(1, 2, 3,
{
success: function(e) {
$.each(e, function(i, n) { alert(n); });
},
dataType: "json"
})
后臺:
[Green.Utility.jQueryInvokeMethod()]
public static int[] TestArrayJson(int p1, int p2, int p3)
{
return new int[] { p1, p2, p3 };
}
效果:
_Default.TestArrayxml("key", "value",
{
success: function(e) {
alert(e.key);
alert(e.Value);
},
dataType: "json"
})
后臺:
[Green.Utility.jQueryInvokeMethod()]
public static Test TestArrayxml(string key,string value)
{
return new Test() { key=key,Value=value};
}
效果:
代碼-jQueryInvokeMethodAttribute (此處只做標(biāo)示方法處理,所以為空):
復(fù)制代碼 代碼如下:
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false,Inherited=false)]
public class jQueryInvokeMethodAttribute : Attribute
{
}
代碼-jQueryAjaxUtility(分注冊腳本和調(diào)用ajax事件):
復(fù)制代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Green.Utility
{
public class jQueryAjaxUtility
{
public static string AjaxInvokeParam = "AjaxInvoke";
public static string AjaxInvokeValue = "1";
public static string ResponseCharset = "UTF-8";
protected static System.Web.UI.Page Page
{
get
{
return System.Web.HttpContext.Current.Handler as System.Web.UI.Page;
}
}
public static void RegisterClientAjaxScript(Type type)
{
if (Page != null)
{
if (System.Web.HttpContext.Current.Request[AjaxInvokeParam] == AjaxInvokeValue)
{
RegisterAjaxInvokeEvent(type);
}
else
{
RegisterAjaxInvokeScript(type);
}
}
}
protected static void RegisterAjaxInvokeScript(Type type)
{
Page.ClientScript.RegisterClientScriptBlock(type.GetType(), type.GetType().FullName + "_" + typeof(jQueryAjaxUtility).FullName + "_AjaxInvokeDefaultOption", "window.defaultAjaxOption={type:'GET',cache:false, dataType:'text'};", true);
if (!jQueryUtilityCache.Current.Exists(type))
{
var methodinfo = type.GetMethods(System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public).Where(t =>
{
var attrs = t.GetCustomAttributes(typeof(jQueryInvokeMethodAttribute), false);
if (attrs != null && attrs.Length > 0)
return true;
return false;
}).ToList();
if (methodinfo != null && methodinfo.Count > 0)
{
System.Text.StringBuilder sb = new StringBuilder();
sb.AppendFormat(" window.{0}=function(){{}}; ", type.Name);
methodinfo.ForEach(t =>
{
var parameters = t.GetParameters().Select(p => p.Name).ToArray();
sb.AppendFormat(" {2}.{0} = function ({1} ajaxOption) {{", t.Name, parameters.Count() > 0 ? string.Join(",", parameters) + "," : "", type.Name);
sb.Append("if(ajaxOption==null||typeof ajaxOption=='undefined'){ajaxOption={};};");
var url = Page.Request.RawUrl.IndexOf("?") == -1 ? Page.Request.RawUrl : Page.Request.RawUrl.Substring(0, Page.Request.RawUrl.IndexOf("?") );
sb.AppendFormat("ajaxOption.url = '{0}';", url);
var data = "''";
if (parameters.Count() > 0)
{
data = (string.Join(" ", parameters.Select(p => string.Format("'&{0}=' + {0}+", p)).ToArray()));
data= data.TrimEnd('+');
}
sb.AppendFormat("ajaxOption.data = 'method={1}&rn={4}&{2}={3}'+{0};", data, t.Name, AjaxInvokeParam, AjaxInvokeValue,Guid.NewGuid().ToString());
sb.Append("ajaxOption= jQuery.extend(window.defaultAjaxOption,ajaxOption);");
sb.Append("jQuery.ajax(ajaxOption);};");
});
jQueryUtilityCache.Current.AddScript(type, sb.ToString());
}
}
var script = jQueryUtilityCache.Current.GetScript(type);
Page.ClientScript.RegisterClientScriptBlock(type.GetType(), type.GetType().FullName + "_" + typeof(jQueryAjaxUtility).FullName + "_AjaxInvoke", script, true);
}
protected string GenertorScript(Type type)
{
return string.Empty;
}
protected static void RegisterAjaxInvokeEvent(Type type)
{
var Request = System.Web.HttpContext.Current.Request;
var Response = System.Web.HttpContext.Current.Response;
var method = Request["method"];
if (string.IsNullOrEmpty(method))
return;
Response.Clear();
var methodinfo = type.GetMethod(method, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
if (methodinfo != null)
{
Response.Charset = ResponseCharset;
Response.ContentType = string.Join(",", Request.AcceptTypes);
var param = methodinfo.GetParameters();
object[] objs = new object[param.Length];
var i = 0;
param.ToList().ForEach(t =>
{
objs[i++] = Convert.ChangeType(Request[t.Name], t.ParameterType);
});
var obj = methodinfo.Invoke(null, objs);
if (obj != null)
{
//序列化
if (!obj.GetType().IsValueType && obj.GetType() != typeof(string))
{
if (Request.AcceptTypes.Contains("text/xml"))
{
Response.Write(Green.Utility.SerializerUtility.XmlSerializer(obj));
}
else if (Request.AcceptTypes.Contains("application/json"))
{
Response.ContentType = "application/json, text/javascript, */*";
Response.Write(Green.Utility.SerializerUtility.JsonSerializer(obj));
}
else
{
Response.Write(obj);
}
}
else
{
Response.Write(obj);
}
}
Response.Flush();
Response.Close();
Response.End();
}
}
}
}
為了考慮反射的性能,加入了類級注冊腳本方法緩存處理jQueryUtilityCache,具體見demo。
測試:
html:
復(fù)制代碼 代碼如下:
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="button" />
</div>
</form>
后臺方法注冊Page_Load
復(fù)制代碼 代碼如下:
Green.Utility.jQueryAjaxUtility.RegisterClientAjaxScript(typeof(_Default));
1:
前臺:
復(fù)制代碼 代碼如下:
_Default.Test("ajax",
{
success: function(e) {
alert(e);
},
dataType: "text"
});
后臺:
復(fù)制代碼 代碼如下:
[Green.Utility.jQueryInvokeMethod()]
public static string Test(string str)
{
return "hello:" + str;
}
效果:
復(fù)制代碼 代碼如下:
_Default.TestArrayJson(1, 2, 3,
{
success: function(e) {
$.each(e, function(i, n) { alert(n); });
},
dataType: "json"
})
后臺:
復(fù)制代碼 代碼如下:
[Green.Utility.jQueryInvokeMethod()]
public static int[] TestArrayJson(int p1, int p2, int p3)
{
return new int[] { p1, p2, p3 };
}
效果:
復(fù)制代碼 代碼如下:
_Default.TestArrayxml("key", "value",
{
success: function(e) {
alert(e.key);
alert(e.Value);
},
dataType: "json"
})
后臺:
復(fù)制代碼 代碼如下:
[Green.Utility.jQueryInvokeMethod()]
public static Test TestArrayxml(string key,string value)
{
return new Test() { key=key,Value=value};
}
效果:
最后看看FireBug中ajax http頭信息:
附錄:代碼下載
作者:破 狼 (cnblogs)
相關(guān)文章
JQuery獲取或設(shè)置ckeditor的數(shù)據(jù)(示例代碼)
JQuery獲取或設(shè)置ckeditor的數(shù)據(jù)(示例代碼)。需要的朋友可以過來參考下,希望對大家有所幫助2013-11-11jquery+swiper組件實現(xiàn)時間軸滑動年份tab切換效果
這篇文章主要介紹了jquery+swiper組件實現(xiàn)時間軸滑動年份tab切換效果,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-12-12jquery.validate自定義驗證用法實例分析【成功提示與擇要提示】
這篇文章主要介紹了jquery.validate自定義驗證用法,結(jié)合實例形式分析了jQuery成功提示與擇要提示驗證操作相關(guān)實現(xiàn)與使用技巧,需要的朋友可以參考下2020-06-06