AJAX下用戶端調用服務端頁面方法

來源:互聯網
上載者:User

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等

本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/weiky626/archive/2007/07/14/1690378.aspx

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.