无为清净楼资源网 Design By www.qnjia.com
在某项目中,设计模板字段引擎,采用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)

标签:
jQuery,Ajax

无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。