方法一:直接使用调用
前台JS:
var methodStr = "";
alert(methodStr);
后头方法:
public static string BehindMethod()
{
return "这是一个后台的方法";
}
方法二:用ajax调用
前台js:
var params = '{ext:"p9hp"}'; //参数,注意参数名要注意和后台方法参数名要一致
$(function(){
$("#btnOk").click(function(){
$.ajax({
type:"POST", //请求方式
url:"AjaxDemo.aspx/GetImg", //请求路径:页面/方法名字
data: params, //参数
dataType:"text",
contentType:"application/json; charset=utf-8",
beforeSend:function(XMLHttpRequest){
$("#tips").text("开始调用后头方法获取图片路径,请等待");
$("#imgFood").attr("src","image/loading.gif");
},
success:function(msg){ //成功
$("#imgFood").attr("src",eval("("+msg+")").d);
$("#tips").text("调用方法结束");
},
error:function(obj, msg, e){ //异常
alert("OH,NO");
}
});
});
});
页面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;
}