javascript 调用后台方法

365dots 2025-06-28 05:41:30 作者: admin 阅读: 5474
javascript 调用后台方法

方法一:直接使用<%=%>调用

前台JS:

后头方法:

public static string BehindMethod()

{

return "这是一个后台的方法";

}

方法二:用ajax调用

前台js:

页面html:

后台方法:

[System.Web.Services.WebMethod]

public static string GetImg(string ext)

{

System.Threading.Thread.Sleep(5000);//为了有点等待的效果,延迟5秒

StringComparer sc = StringComparer.OrdinalIgnoreCase;

string[] extArr = new string[] { "php", "asp", "aspx", "txt", "bmp" };

bool f = extArr.Any(s=>sc.Equals(s,ext)); //判断传入的后缀名是否存在

if (f)

{

return "image/54222860.jpg";

}

return "image/star1.jpg";

}

方法三:AjaxPro (也是ajax)

第一步:下载AjaxPro.dll(或者AjaxPro.2.dll),并且添加引用到项目

第二步:修改配置文件web.config

第三步:对AjaxPro在页Page_Load事件中进行运行时注册。如:

protected void Page_Load(object sender, EventArgs e)

{

AjaxPro.Utility.RegisterTypeForAjax(typeof(AjaxDemo)); //注册

}

第四步:创建服务器方法,并且用[AjaxPro.AjaxMethod]标注

[AjaxPro.AjaxMethod]

public string GetImgByAjaxPro()

{

return "image/54222860.jpg";

}第五步:前台JS的调用:

function GetMethodByAjaxPro() {

var a = JustTest.AjaxDemo.GetImgByAjaxPro();//JustTest是当前的名字空间,AjaxDemo表示后台类

document.getElementById("imgAjaxPro").src = a.value;

}

相关推荐