jQuery Ajax 仿AjaxPro.Utility.RegisterTypeForAjax辅助方法


Posted in Javascript onSeptember 27, 2011

在某项目中,设计模板字段引擎,采用html+jquery实现,这里的数据就难免需要ajax获取,但是团队对于js掌握不一,所以我写了下面辅助类,可以像ajaxpro一样简化ajax的开发。
代码-jQueryInvokeMethodAttribute (此处只做标示方法处理,所以为空):

[AttributeUsage(AttributeTargets.Method, AllowMultiple=false,Inherited=false)] 
public class jQueryInvokeMethodAttribute : Attribute 
{ 
}

代码-jQueryAjaxUtility(分注册脚本和调用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; 
}

效果:

jQuery Ajax 仿AjaxPro.Utility.RegisterTypeForAjax辅助方法
2:前台ajax:

_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 }; 
}

效果:

jQuery Ajax 仿AjaxPro.Utility.RegisterTypeForAjax辅助方法 
3:前台ajax:

_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}; 
}

效果:

jQuery Ajax 仿AjaxPro.Utility.RegisterTypeForAjax辅助方法

最后看看FireBug中ajax http头信息:

jQuery Ajax 仿AjaxPro.Utility.RegisterTypeForAjax辅助方法
附录:代码下载
作者:破 狼 (cnblogs)

Javascript 相关文章推荐
出现“不能执行已释放的Script代码”错误的原因及解决办法
Aug 29 Javascript
替代window.event.srcElement效果的可兼容性的函数
Dec 18 Javascript
JavaScript实现QueryString获取GET参数的方法
Jul 02 Javascript
JavaScript 函数惰性载入的实现及其优点介绍
Aug 12 Javascript
JavaScript的Vue.js库入门学习教程
May 23 Javascript
javascript实现鼠标点击页面 移动DIV
Dec 02 Javascript
利用JS实现简单的瀑布流加载图片效果
Apr 22 Javascript
vue.js在标签属性中插入变量参数的方法
Mar 06 Javascript
VUE基于NUXT的SSR 服务端渲染
Nov 30 Javascript
Node.js中package.json中库的版本号(~和^)
Apr 02 Javascript
深入解析微信小程序开发中遇到的几个小问题
Jul 11 Javascript
javascript前端和后台进行数据交互方法示例
Aug 07 Javascript
Ext.get() 和 Ext.query()组合使用实现最灵活的取元素方式
Sep 26 #Javascript
一个挺有意思的Javascript小问题说明
Sep 26 #Javascript
Jquery之Ajax运用 学习运用篇
Sep 26 #Javascript
jQuery+CSS 实现随滚动条增减的汽水瓶中的液体效果
Sep 26 #Javascript
在Windows上安装Node.js模块的方法
Sep 25 #Javascript
javascript权威指南 学习笔记之null和undefined
Sep 25 #Javascript
利用JS自动打开页面上链接的实现代码
Sep 25 #Javascript
You might like
通用PHP动态生成静态HTML网页的代码
2010/03/04 PHP
php处理斐波那契数列非递归方法
2012/02/04 PHP
php生成EAN_13标准条形码实例
2013/11/13 PHP
PHP中文编码小技巧
2014/12/25 PHP
PHP explode()函数的几个应用和implode()函数有什么区别
2015/11/05 PHP
PHP编写登录验证码功能 附调用方法
2016/05/19 PHP
浅析PHP数据导出知识点
2018/02/17 PHP
js弹出层(jQuery插件形式附带reLoad功能)
2013/04/12 Javascript
你必须知道的JavaScript 变量命名规则详解
2013/05/07 Javascript
JS计算网页停留时间代码
2014/04/28 Javascript
javascript中alert()与console.log()的区别
2015/08/26 Javascript
基于jQuey实现鼠标滑过变色(整行变色)
2015/12/07 Javascript
使用Angular.js实现简单的购物车功能
2016/11/21 Javascript
JavaScript中定义对象原型的两种使用方法
2016/12/15 Javascript
微信小程序图片横向左右滑动案例
2017/05/19 Javascript
详解vue引入子组件方法
2019/02/12 Javascript
jQuery选择器之基本过滤选择器用法实例分析
2019/02/19 jQuery
Vue框架下引入ActiveX控件的问题解决
2019/03/25 Javascript
React实现todolist功能
2020/12/28 Javascript
详细介绍Python函数中的默认参数
2015/03/30 Python
python链接oracle数据库以及数据库的增删改查实例
2018/01/30 Python
利用pandas读取中文数据集的方法
2018/07/25 Python
Python 使用 docopt 解析json参数文件过程讲解
2019/08/13 Python
python使用sklearn实现决策树的方法示例
2019/09/12 Python
使用Python pip怎么升级pip
2020/08/11 Python
python调用百度API实现人脸识别
2020/11/17 Python
CSS3 对过渡(transition)进行调速以及延时
2020/10/21 HTML / CSS
办理护照介绍信
2014/01/16 职场文书
优秀毕业生自我鉴定
2014/01/19 职场文书
普通话演讲稿
2014/09/03 职场文书
小学教师自我剖析材料
2014/09/29 职场文书
三下乡个人总结
2015/03/04 职场文书
laravel添加角色和模糊搜索功能的实现代码
2021/06/22 PHP
SQL Server中常用截取字符串函数介绍
2022/03/16 SQL Server
零基础学java之循环语句的使用
2022/04/10 Java/Android
python实现学生信息管理系统(面向对象)
2022/06/05 Python