Ajax是时下热门的技术
asp.net框架下实现ajax有很多方式
今天想介绍一下自己设计的ajax实现方式(如有雷同纯属巧合)
首先看一个封装类,AjaxUtils
这个类封装了调用对象方法的反射机制.
传统ajax回传,对不同的方法调用会使用不同的url或webService
现在通过这个方法可以直接调用某个控件的内部方法
也就是说,可以调用任意页面上任意控件的任意方法,而且可以一次调用多个方法
public class AjaxUtils
{
public static string CacheKey(Type type, string methodName)
{
return String.Format("AjaxMethod::Type:{0}-Method:{1}", type.Name, methodName);
}
public static void CallAjaxMethod(object target, params string[] methodName)
{
CallAjaxMethod(target, true, methodName);
}
public static void CallAjaxMethod(object target,bool userCache,params string[] methodName)
{
if (methodName == null || methodName.Length == 0)
return;
List<MethodBase> ajaxMethods = new List<MethodBase>();
BindingFlags bfs = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.ExactBinding;
for (int i = 0; i < methodName.Length; i++)
{
if (string.IsNullOrEmpty(methodName[i]))
continue;
Type type = target.GetType();
MethodBase method = null;
string cacheKey = CacheKey(type, methodName[i]);
if (userCache)
{
method = WebCache.Get(cacheKey) as MethodBase;
}
if (method == null)
{
RuntimeMethodHandle methodHandle = type.GetMethod(methodName[i], bfs).MethodHandle;
method = MethodInfo.GetMethodFromHandle(methodHandle);
WebCache.Insert(cacheKey, method, WebCache.HourFactor * 24);//将请求的方法缓存起来,下次不再通过反射寻找方法,而是直接调用
}
if (method != null)
ajaxMethods.Add(method);
}
if (ajaxMethods.Count == 0)
return;
HttpResponse Response = HttpContext.Current.Response;
HttpRequest Request = HttpContext.Current.Request;
Response.Cache.SetNoStore();
Response.ContentType = "text/xml"; //返回xml响应
//xml响应格式:
//<ajax-response>
// <response>
// </response>
//</ajax-response>
StringBuilder builder = new StringBuilder("<ajax-response>");
foreach (MethodInfo method in ajaxMethods) //循环调用方法
{
try
{
object obj = null;
try
{
obj = method.Invoke(target, new object[] { target, new EventArgs() });
}
catch (MethodAccessException ex)
{
Response.Clear();
Response.StatusCode = 500;
Response.StatusDescription = "ajax调用产生异常";
}
//如果方法有返回值,将返回值以xml子节点的形式返回
if (obj != null)
{
string str = obj.ToString();
//检查是否具有<response> 和 </response>元素,如果没有,添加元素
if (!Regex.IsMatch(str, @"(^<response[/s]*>)|(^<response/s[^<>]+>).*?</response>"))
{
builder.Append("<response id=/"");
builder.Append(method.Name);//表明xml响应是哪个方法返回的
builder.Append("/" type=/"");
builder.Append();//这里可以声明一些返回类型(如html,script等等)
builder.Append("/" name=/"");
builder.Append(method.Name);
builder.Append("/">");
builder.Append(str);
builder.Append("</response>");
}
else
{
builder.Append(str);
}
}
}
catch(Exception ex)
{
string str = ex.Message;
}
}
builder.Append("</ajax-response>");
Response.Write(builder.ToString());
Response.End();
}
}
未完待续