创建web窗体ajax_data.aspx
public partial class ajax_data : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string action = Request.QueryString["action"];
if (!string.IsNullOrEmpty(action))
{
Type type = this.GetType();
MethodInfo method = type.GetMethod(action, BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod);
method.Invoke(this, null);
}
else
{
OutMsg("方法错误", 0);
}
}
#region 获取数据
/// <summary>
/// 获取数据
/// </summary>
public void GetData()
{
int.TryParse(Request["pagesize"] + "", out int PageSize);
int.TryParse(Request["pageindex"] + "", out int PageIndex);
string data = $"你要获取的数据,页码:{PageIndex},大小:{PageSize}";
OutMsg(data, 1);
}
#endregion
#region 返回信息
/// <summary>
/// 返回信息
/// </summary>
/// <param name="msg"></param>
/// <param name="state"></param>
private void OutMsg(string data, int state)
{
var res = new { state = state, data = data };
Response.Write(JObject.FromObject(res));
Response.End();
}
#endregion
}
前台请求示例: 传入的action为ajax_data后台代码中的方法名称
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<input type="button" id="btn" value="点击获取数据" />
<script src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$('#btn').click(function () {
$.post('/ajax_data.aspx?action=GetData', { pageindex: 1, pagesize: 4 }, function (res) {
if (res != null && res.data != null && res.state == 1) {
console.log("数据为", res.data);
}
}, 'json');
})
</script>
</body>
</html>
调用结果: