JavaScript调用后台的三种方法实例_javascript技巧

WBOY
Release: 2016-05-16 17:19:55
Original
980 people have browsed it

方法一:直接使用调用

前台JS:

复制代码代码如下:


后头方法:

复制代码代码如下:

public static string BehindMethod()
{
return "这是一个后台的方法";
}

方法二:用ajax调用

前台js:

复制代码代码如下:



页面html:

复制代码代码如下:





JavaScript调用后台的三种方法实例_javascript技巧






后台方法:

复制代码代码如下:

[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;
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!