在项目中让Ajax面向对象 (一)

    Ajax应用不是一个什么新话题了,使用的人越来越多,现在各种流行JS框架全包框了AJAX处理,使用时不用过多考虑浏览器的兼容性了,传统的做法还是在客户端使用类似$post方式发送数据,在服务端page_load中得到一个传递的查询字符串的一个特殊标记来相应客户端ajax事件。ajaxpro做的不错,解决了我们的ajax面向对象,可与prototype和jquery框架结合时会产生一些问题。如果一边可以使用ajaxpro的方式做ajax传递,一边方便使用jquery各种插件,是个不错主意。

    分析ajaxpro,可以在实现服务端自己定义处理ajax事件,而在客户端写一个jquery插件。

    首先对服务端处理Ajax方法加入自定义属性(Attribute)。主要作用是用来我们在反射时方便找到那些方法是处理ajax方法。

   

1 [AjaxMethod]
2 publicint TestMethod(int x, int y)
3 {
4 int m =0;
5 m = x + y;
6 return m;
7 }

     形式如上面的。AjaxMethod是自定义属性(Attribute) .关于如何实现自定义属性可以在网上找到资料很多。

    反射读取自定义 AjaxMethod方法并生成一段JS脚本,是将标记有AjaxMethod全部方法。

    一个Js脚本如何定义一个类 有两种方法 json 和 function 方式。如var classname = function() {}; classname.method1 = function(arg){}。我用了后一种实现。

   

代码
1 StringBuilder scriptBuilder =new StringBuilder(4096);
2 scriptBuilder.Append("\n<script type=\"text/javascript\">\n");
3 scriptBuilder.AppendFormat("var {0} = function(){{}};\n", classname);//classname是我们的类名
4  
5 MethodInfo[] methods = page.GetMethods(BindingFlags.Instance | BindingFlags.Public);
6 MethodInfo methodInfo =null;
7 int methodCount =0;
8
9 for (int i =0, count = methods.Length; i < count; i++)
10 {
11 methodInfo = methods[i];
12 object[] attributes = methodInfo.GetCustomAttributes(typeof(AjaxMethodAttribute), true);
13 if (attributes !=null&& attributes.Length >0)
14 {
15 AjaxMethodAttribute methodAttribute = attributes[0] as AjaxMethodAttribute;
16 string clientSideName = methodInfo.Name;
17 //clientSideName 方法名,客户段与服务段的方法名同名
18   scriptBuilder.AppendFormat(@"{0}.{1} = function(", classname, clientSideName);
19 ParameterInfo[] parameters = methodInfo.GetParameters();
20 ParameterInfo paramInfo =null;
21 StringBuilder scriptParameters =new StringBuilder(100);
22
23 for (int j =0, jCount = parameters.Length; j < jCount; j++)
24 {
25 paramInfo = parameters[j];
26 scriptBuilder.Append(paramInfo.Name +",");
27 scriptParameters.Append(","+ paramInfo.Name);
28 }
29
30 scriptBuilder.Append("clientCallBack){\n");//客户端的回调方法
31 //以下是我写的一个jquery插件,包装了原有的$post
32 scriptBuilder.AppendFormat
33 ("JqAjax.Post(\"{0}\",\"{1}\",[{2}],{3},\"{4}\");}}\n",
34 page.BaseType.FullName, methodInfo.Name, scriptParameters.ToString().Substring(1),
35 "clientCallBack",url);
36
37 }
38 }
39 scriptBuilder.Append("</script>");
40 if (methodCount ==0) returnstring.Empty;
41 return scriptBuilder.ToString();

   以上的方法处理会产生一个格式如:Class.method(paramaters)。把这段脚本生成后放到页面中,当再使用ajax调用时看起来更像是一种面向对象方式了。

原文地址:https://www.cnblogs.com/shouhongxiao/p/1713625.html