<body>
<h1>index</h1>
<input type="button" value="GetData" onclick="getData()" />
<span id="result"></span>
</body>
<script type="text/javascript">
function getData() {
$.get("GetData", function (data) {
$("#result").text(data);
});
}
</script>
public class AjaxController : Controller
{
public ActionResult GetData()
{
if(Request.IsAjaxRequest())
{
return Content("data");
}
return View();
}
}
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="获取回调结果" onclick="callServer()" />
<span id="result" style="color:Red;"></span>
</div>
</form>
</body>
<script type="text/javascript">
function getCallbackResult(result){
document.getElementById("result").innerHTML = result;
}
</script>
public partial class Test1 : System.Web.UI.Page, ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
//客户端脚本Manager
ClientScriptManager scriptMgr = this.ClientScript;
//获取回调函数,getCallbackResult就是回调函数
string functionName = scriptMgr.GetCallbackEventReference(this, "", "getCallbackResult", "");
//发起请求的脚本,callServer就是点击按钮事件的执行函数
string scriptExecutor = "function callServer(){" + functionName + ";}";
//注册脚本
scriptMgr.RegisterClientScriptBlock(this.GetType(), "callServer", scriptExecutor, true);
}
//接口方法
public string GetCallbackResult()
{
return "callback result";
}
//接口方法
public void RaiseCallbackEvent(string eventArgument)
{
}
}
public void ProcessRequest(HttpContext context)
{
Page page = new Page();
Control control = page.LoadControl("~/PageOrAshx/UserInfo.ascx");
if (control != null)
{
StringWriter sw = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(sw);
control.RenderControl(writer);
string html = sw.ToString();
context.Response.Write(html);
}
}
public class PageBase : Page
{
public override void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
if (string.Compare(request.Headers["AjaxFlag"],"AjaxFlag",0) == 0)
{
string methodName = request.Headers["MethodName"];
if (string.IsNullOrEmpty(methodName))
{
EndRequest("MethodName标记不能为空!");
}
Type type = this.GetType().BaseType;
MethodInfo info = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
if (info == null)
{
EndRequest("找不到合适的方法调用!");
}
string data = info.Invoke(this, null) as string;
EndRequest(data);
}
base.ProcessRequest(context);
}
private void EndRequest(string msg)
{
HttpResponse response = this.Context.Response;
response.Write(msg);
response.End();
}
}
public partial class Test1 : PageBase
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string GetData()
{
return "213";
}
}
function getData(){
$.ajax({
headers:{"AjaxFlag":"XHR","MethodName":"GetData"},
success:function(data){
$("#result").text(data);
}
});
}
public class AjaxMethodAttribute : Attribute
{
}
public class CacheMethodInfo
{
public string MethodName { get; set; }
public MethodInfo MethodInfo { get; set; }
public ParameterInfo[] Parameters { get; set; }
}
public class PageBase : Page
{
private static Hashtable _ajaxTable = Hashtable.Synchronized(new Hashtable());
public override void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
if (string.Compare(request.Headers["AjaxFlag"],"XHR",true) == 0)
{
InvokeMethod(request.Headers["MethodName"]);
}
base.ProcessRequest(context);
}
/// <summary>
/// 反射执行函数
/// </summary>
/// <param name="methodName"></param>
private void InvokeMethod(string methodName)
{
if (string.IsNullOrEmpty(methodName))
{
EndRequest("MethodName标记不能为空!");
}
CacheMethodInfo targetInfo = TryGetMethodInfo(methodName);
if (targetInfo == null)
{
EndRequest("找不到合适的方法调用!");
}
try
{
object[] parameters = GetParameters(targetInfo.Parameters);
string data = targetInfo.MethodInfo.Invoke(this, parameters) as string;
EndRequest(data);
}
catch (FormatException)
{
EndRequest("参数类型匹配发生错误!");
}
catch (InvalidCastException)
{
EndRequest("参数类型转换发生错误!");
}
catch (ThreadAbortException)
{
}
catch (Exception e)
{
EndRequest(e.Message);
}
}
/// <summary>
/// 获取函数元数据并缓存
/// </summary>
/// <param name="methodName"></param>
/// <returns></returns>
private CacheMethodInfo TryGetMethodInfo(string methodName)
{
Type type = this.GetType().BaseType;
string cacheKey = type.AssemblyQualifiedName;
Dictionary<string, CacheMethodInfo> dic = _ajaxTable[cacheKey] as Dictionary<string, CacheMethodInfo>;
if (dic == null)
{
dic = new Dictionary<string, CacheMethodInfo>();
MethodInfo[] methodInfos = (from m in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
let ma = m.GetCustomAttributes(typeof(AjaxMethodAttribute), false)
where ma.Length > 0
select m).ToArray();
foreach (var mi in methodInfos)
{
CacheMethodInfo cacheInfo = new CacheMethodInfo();
cacheInfo.MethodName = mi.Name;
cacheInfo.MethodInfo = mi;
cacheInfo.Parameters = mi.GetParameters();
dic.Add(mi.Name, cacheInfo);
}
_ajaxTable.Add(cacheKey, dic);
}
CacheMethodInfo targetInfo = null;
dic.TryGetValue(methodName, out targetInfo);
return targetInfo;
}
/// <summary>
/// 获取函数参数
/// </summary>
/// <param name="parameterInfos"></param>
/// <returns></returns>
private object[] GetParameters(ParameterInfo[] parameterInfos)
{
if (parameterInfos == null || parameterInfos.Length <= 0)
{
return null;
}
HttpRequest request = this.Context.Request;
NameValueCollection nvc = null;
string requestType = request.RequestType;
if (string.Compare("GET", requestType, true) == 0)
{
nvc = request.QueryString;
}
else
{
nvc = request.Form;
}
int length = parameterInfos.Length;
object[] parameters = new object[length];
if (nvc == null || nvc.Count <= 0)
{
return parameters;
}
for (int i = 0; i < length; i++)
{
ParameterInfo pi = parameterInfos[i];
string[] values = nvc.GetValues(pi.Name);
object value = null;
if (values != null)
{
if (values.Length > 1)
{
value = String.Join(",", values);
}
else
{
value = values[0];
}
}
if (value == null)
{
continue;
}
parameters[i] = Convert.ChangeType(value, pi.ParameterType);
}
return parameters;
}
private void EndRequest(string msg)
{
HttpResponse response = this.Context.Response;
response.Write(msg);
response.End();
}
}
public string GetData3(int i, double d, string str)
{
string[] datas = new string[] { i.ToString(), d.ToString(), str };
return "参数分别是:" + String.Join(",", datas);
}
function getData3(){
$.ajax({
headers:{"AjaxFlag":"XHR","MethodName":"GetData3"},
data:{"i":1,"d":"10.1a","str":"hehe"},
success:function(data){
$("#result").text(data);
}
});
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有