.net 使用$.ajax实现从前台调用后台方法(包含静态方法和非静态方法调用)
/*---------------后台必须是静态方法-------------*/
/*---------------前台*-----------------/
$(function() {
$("#btnOK").click(function() {
$.ajax({
type: "Post",
url: "demo.aspx/GetStr",
//方法传参的写法一定要对,str为形参的名字,str2为第二个形参的名字
data: "{'str':'I am','str2':'XXX'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//return data
alert(data.d);
},
error: function(err) {
alert(err);
}
});
//禁用按钮的提交
return false;
});
});
/*---------------前台*-----------------/
/*---------------后台*-----------------/
[WebMethod]
public static string GetStr(string str, string str2)
{
return str + str2;
}
/*---------------后台*-----------------/
/*---------------后台必须是静态方法-------------*/
/*---------------后台可以是非静态方法-----------*/
/*---------------前台-------------------------*/
$.ajax({
type: "POST",
url: "McuHandler.ashx",
data: { page: 'ActivityEnrolment.aspx', method: 'GetActivityItemById', val: coaInfo },
success: function (msg) {
if ($("#TravelInsuranceValueLabelForInsert")[0] != undefined) {
$("#TravelInsuranceValueLabelForInsert")[0].innerText = msg;
}
if ($("#TravelInsuranceValueLabelForEdit")[0] != undefined){
$("#TravelInsuranceValueLabelForEdit")[0].innerText = msg;
}
}
});
/*---------------前台-------------------------*/
/*---------------后台-------------------------*/
1.新增一个ashx文件
2.在ProcessRequest方法中调用非静态方法并返回值
public void ProcessRequest(HttpContext context)
{
var val = context.Request.Form["val"];//GET方式提交就用context.Request.QueryString["val"]
var page = context.Request.Form["page"];
var method = context.Request.Form["method"];
var rtnVal = string.Empty;
context.Response.ContentType = "text/plain";
switch (page)
{
case "ActivityEnrolment.aspx":
switch (method)
{
case "GetActivityItemById":
rtnVal = GetActivityItemById(val);
context.Response.Write(rtnVal.ToFormatDecimalText(DecimalPlace.Two, true));
break;
default:
context.Response.Write("");
break;
}
break;
default:
context.Response.Write("");
break;
}
/*---------------后台-------------------------*/
/*---------------后台可以是非静态方法-----------*/