您现在的位置: 365建站网 > 365文章 > AJAX下客户端调用服务端页面方法

AJAX下客户端调用服务端页面方法

文章来源:365jz.com     点击数:580    更新时间:2009-10-09 10:37   参与评论

1.客户端代码如下:

//函数功能:客户端调用页面服务端方法

//示例:

//参数说明:

//isStaticMethod:是否是静态方法

//methodName:方法名称

//methodParamter:[可选]方法参数,必须是类型MethodParamter的实例或者null值(无参数)
//callBackMethod:[可选]方法调用完后回调的客户端方法,客户端方法形式为 function callBackMethod(result){},result是个json对象,例如:function HandleCheckListResult(result){},参数值就是'HandleCheckListResult'
//assemblyAndClassName:[可选]页面服务端所在组件和类名,形式为: 'AssemblyName|ClassFullName',例如: Weiky.dll|Weiky.AccessoriesForm'
function CallPageMethod(isStaticMethod,methodName,methodParamter,callBackMethod,assemblyAndClassName)
...{
    if(methodParamter && typeof(methodParamter.AddBoolParamter) != 'function')
    ...{
        alert(“参数methodParamter必须是类型MethodParamter的实例或者null值");
        return;
    }
    if(assemblyAndClassName == null)
    ...{
        if(typeof(AssemblyAndClassName) != 'undefined')
        ...{
            assemblyAndClassName = AssemblyAndClassName;
        }
        else
        ...{
            alert("未提供页面服务端所在组件和类名");
            return;
        }
    }
    try
    ...{
        MyWebService.CallPageMethod(assemblyAndClassName,isStaticMethod,methodName,methodParamter?methodParamter.ToJson():null,methodParamter.ToType(),callBackMethod?callBackMethod:'', CallBackByWebService,HandleServiceMethodCallError);                                       
    }
    catch(err)
    ...{
        alert('将参数转换成JSON对象失败!');
    }
}

function CallBackByWebService(result)
...{
    var json = ConvertStringToJson(result);
    if(json.Type != 0)
    ...{
        ShowMessageBox2(json);
    }
    else
    ...{
        var callBackMethod = json.HighlevelMessage;
        if(callBackMethod != '')
        ...{
            json.HighlevelMessage = '';
            json.Message = ReplaceString(json.Message,'┍',' ');
            eval(callBackMethod + '(json)');
        }
    }
}

function MethodParamter()
...{
    var paramter = '';
    var json = null;
   
    this.AddStringParamter = function (value)
    ...{
        AddParamter('string',ReplaceString(ReplaceString(value,'"','\"'),' ','┍'));
    }
   
    this.AddGuidParamter = function (value)
    ...{
        AddParamter('guid',value);
    }
   
    this.AddDateParamter = function (value)
    ...{
        AddParamter('date',value);
    }
   
    this.AddIntParamter = function (value)
    ...{
        AddParamter('int',value);
    }
   
    this.AddDecimalParamter = function (value)
    ...{
        AddParamter('decimal',value);
    }
   
    this.AddBoolParamter = function (value)
    ...{
        AddParamter('bool',value);
    }
   
    function AddParamter(type,value)
    ...{
        if(paramter != '')
        ...{
            paramter += ','
        }
        paramter += '{"Type":"' + type + '","Value":"' + value + '"}';
    }
   
    this.AddJsonParamter = function (p)
    ...{
        json = p;
    }
   
    this.ToJson = function ()
    ...{
        if(json)
        ...{
            return json;
        }
        if(paramter != '')
        ...{
            return eval('[' + paramter + ']');
        }
       
        return null;
    }
   
    this.ToType = function ()
    ...{
        return json?1:0;
    }
}
2.服务端webservice提供给ScriptManager控件,webservice代码如下:

[System.Web.Script.Services.ScriptService]
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    public class MyWebService : System.Web.Services.WebService
    ...{
[WebMethod(EnableSession = true)]
        public string CallPageMethod(string assemblyAndClassName, bool isStaticMethod, string methodName, object paramtersPackage,int mpType,string callBackMethod)
        ...{
            try
            ...{
                object result = "";
                bool succeed = false;
                if (isStaticMethod)
                ...{
                    Type type = GetActualType(assemblyAndClassName);
                    if (type != null)
                    ...{
                        succeed = true;
                        if (mpType == 1)
                        ...{
                            result = type.InvokeMember(methodName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Static, null, null, new object[] ...{ paramtersPackage });
                        }
                        else
                        ...{
                            result = type.InvokeMember(methodName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Static, null, null, GetMethodArgs(paramtersPackage));
                        }
                    }
                }
                else
                ...{
                    object o = WebBase.GetActualInstance(assemblyAndClassName, this.Server.MapPath("~/bin/"));
                    if (o != null)
                    ...{
                        succeed = true;
                        if (mpType == 1)
                        ...{
                            result = o.GetType().InvokeMember(methodName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Instance, null, o, new object[] ...{ paramtersPackage });
                        }
                        else
                        ...{
                            result = o.GetType().InvokeMember(methodName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Instance, null, o, GetMethodArgs(paramtersPackage));
                        }
                    }
                }

                return succeed ? 0 : 1, succeed ? (result == null ? "" : result.ToString()) : string.Format("获取组件信息失败,请检查组件参数{0}是否正确", assemblyAndClassName);
            }
            catch (Exception err)
            ...{
                return err.Message;
            }
        }
private object[] GetMethodArgs(object paramtersPackage)
        ...{
            if (paramtersPackage == null) return null;

            int i = 0;
            object[] args = new object[((object[])paramtersPackage).Length];
            foreach (System.Collections.Generic.Dictionary<string, object> p in (object[])paramtersPackage)
            ...{
                switch (p["Type"].ToString().ToLower())
                ...{
                    case "string":
                        args[i++] = p["Value"].ToString().Replace("┍"," ");
                        break;
                    case "guid":
                        args[i++] = new Guid(p["Value"].ToString());
                        break;
                    case "date":
                        args[i++] = Convert.ToDateTime(p["Value"].ToString());
                        break;
                    case "int":
                        args[i++] = Convert.ToInt32(p["Value"].ToString());
                        break;
                    case "decimal":
                        args[i++] = Convert.ToDecimal(p["Value"].ToString());
                        break;
                    case "bool":
                        args[i++] = Convert.ToBoolean(p["Value"].ToString());
                        break;
                    default:
                        args[i++] = p["Value"];
                        break;
                }
            }
            return args;
        }
 private WebBaseForm GetActualInstanceForm(string assemblyAndClassName)
        ...{
            object o = WebBase.GetActualInstance(assemblyAndClassName,this.Server.MapPath("~/bin/"));
            if (o != null)
            ...{
                if (o is WebBaseForm)
                ...{
                    return (WebBaseForm)o;
                }
            }

            return null;
        }

        private Type GetActualType(string assemblyAndClassName)
        ...{
            if (assemblyAndClassName != "")
            ...{
                string[] ac = assemblyAndClassName.Replace("!", "\").Split('|');
                if (ac.Length == 2)
                ...{
                    ac[0] = WebBase.AddPath(ac[0],this.Server.MapPath("~/bin/"));
                    return System.Reflection.Assembly.LoadFrom(ac[0]).GetType(ac[1]);
                }
            }

            return null;
        }
}
 3.客户端调用示例:

function DataDDL_Change(ddl)
        ...{
            var mp = new MethodParamter();
            mp.AddIntParamter(DropDownList_GetValue(ddl));
            mp.AddIntParamter(EntityObjectId);
            CallPageMethod(true,'GetEntityData',mp,'LoadDataTree');
        }
       
        function LoadDataTree(json)
        ...{
alert(json.Message);
}
总结:通过这样的封装,客户端调用服务端静态/实例方法非常方便,并且不会引起任何页面的postback。上面所用客户端技术有ajax,json等
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (580人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号