前台調用後台函數

來源:互聯網
上載者:User

標籤:http   java   os   io   for   cti   ar   javascript   

 調用 var b = $ajax("WebApplication1._Default.GetDataSet", ["23"]);

js:/*方法全名,參數,類所在的程式集名稱(當方法類所在的命名空間不是程式集名稱時請傳參數來)*/
function $ajax(paramMethod, paramValue, paramAssemblyName) {
    if (!paramMethod) { Dialog.alert("缺少全名稱的方法參數", 1); }
    var result, params = "", assemblyName, className, methodName;
    if (paramValue) for (var i = 0; i < paramValue.length; i++) { params += "&param" + i + "=" + encodeURI(paramValue[i]); }; //擷取參數
    className = paramMethod.substring(0, paramMethod.lastIndexOf(‘.‘));     // 擷取方法所在類名稱
    methodName = paramMethod.substring(paramMethod.lastIndexOf(‘.‘) + 1);   // 擷取方法名稱
    assemblyName = className.substring(0, className.lastIndexOf(‘.‘)); if (paramAssemblyName) assemblyName = paramAssemblyName; // 擷取命名空間名稱
    $.ajax({ url: "/../Ajax.ashx?Assembly=" + assemblyName + "&Class=" + className + "&Method=" + methodName + params, type: "POST", async: false,
        success: function (data) { result = eval("(" + data + ")"); },
        error: function (data) {
            layer.msg(data.responseText, 2, 0);
        }
    });
    return result;
}

Ajax.ashx:

using System; using System.Collections.Generic; using System.Web; using System.Web.SessionState; using System.Data; using System.Reflection; using System.IO; using System.Web.Script.Serialization;

namespace Chengrui.RSP.UILayer {     /// <summary>     /// Ajax 的摘要說明     /// </summary>     public class Ajax : IHttpHandler, IRequiresSessionState     {

        #region public void GetMethod() 擷取參數         /// <summary>         /// 擷取參數         /// </summary>         /// <param name="context">介面內容</param>         /// <param name="paramField">參數</param>         /// <returns></returns>         public string GetRequest(HttpContext context, string paramField)         {             try { return context.Request[paramField] == null || context.Request[paramField].ToString() == "undefined" ? "" : context.Request[paramField].ToString().Trim(); }             catch { return string.Empty; }         }         #endregion

        public void ProcessRequest(HttpContext context)         {             object result = null;             try             {                 string assemblyName = this.GetRequest(context, "Assembly"), className = this.GetRequest(context, "Class"), methodName = this.GetRequest(context, "Method");                                 //擷取程式集                 Type type = null;                 try { Assembly myAssembly = Assembly.Load(assemblyName); type = myAssembly.GetType(className); }                 catch { type = Assembly.GetExecutingAssembly().GetType(className); }

                //找不到程式集,就遍曆基目錄下的所有以Chengrui.RS.命名的程式集,而擷取方法                 if (type == null)                 {                     FileInfo[] arrFileInfo = new DirectoryInfo(AppDomain.CurrentDomain.RelativeSearchPath).GetFiles("Chengrui.RS.*.dll");                     foreach (FileInfo myFile in arrFileInfo) { type = Assembly.Load(myFile.Name.Substring(0, myFile.Name.LastIndexOf(‘.‘))).GetType(className); if (type != null) break; }                 }

                if (type != null)                 {                     System.Reflection.MethodInfo methodInfo = type.GetMethod(methodName);                     if (methodInfo != null)//判斷操作頁面是否有該方法                     {                         object[] args = new object[methodInfo.GetParameters().Length];                         //對方法名的參數進行賦值                         for (int i = 0; i < methodInfo.GetParameters().Length; i++) { args[i] = Convert.ChangeType(this.GetRequest(context, "param" + i.ToString()), methodInfo.GetParameters()[i].ParameterType); }                         //執行方法                         result = methodInfo.Invoke(Activator.CreateInstance(type), args);                     }                     else                         result = "沒有找到【assemblyName:" + assemblyName + "】.【className:" + className + "】.【methodName:" + methodName + "】方法";                 }                 else                     result = "沒有找到【assemblyName:" + assemblyName + "】.【className:" + className + "】類";             }             catch (Exception myEx) { result = myEx.Message; }            // context.Response.Write(CommonMethod.ToJson(result));             context.Response.Write(ToJson(result));         }

        public bool IsReusable         {             get             {                 return false;             }         }

        #region public static string ToJson(object obj)         /// <summary>         /// 轉Json         /// </summary>         /// <param name="obj"></param>         /// <returns></returns>         public static string ToJson(object obj)         {             if (obj == null) obj = string.Empty;             JavaScriptSerializer myJson = new JavaScriptSerializer();             if (obj.GetType().Name == "DataTable")             {                 DataTable myDt = (DataTable)obj;                 string tableName = myDt.TableName == "" ? "TableName1" : myDt.TableName;                 Dictionary<string, object> dic = new Dictionary<string, object>();                 dic.Add(tableName, RowsToDictionary(myDt));                 return myJson.Serialize(dic);             }             else if (obj.GetType().Name == "DataSet")             {                 DataSet myDs = (DataSet)obj;                 Dictionary<string, object> dic = new Dictionary<string, object>();                 for (int i = 0; i < myDs.Tables.Count; i++)                 {                     string tableName = myDs.Tables[i].TableName == "" ? "TableName" + i.ToString() : myDs.Tables[i].TableName;                     dic.Add(tableName, RowsToDictionary(myDs.Tables[i]));                 }                 return myJson.Serialize(dic);             }             else                 return myJson.Serialize(obj);         }

        private static List<Dictionary<string, object>> RowsToDictionary(DataTable table)         {             List<Dictionary<string, object>> objs = new List<Dictionary<string, object>>();             foreach (DataRow dr in table.Rows)             {                 Dictionary<string, object> drow = new Dictionary<string, object>();                 for (int i = 0; i < table.Columns.Count; i++)                 {                     drow.Add(table.Columns[i].ColumnName, dr[i]);                 }                 objs.Add(drow);             }             return objs;         }

      #endregion     } }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.