虽然aspx现在用的越来越少,但是以前的一些项目仍旧是使用WebForm来实现的,我们仍然会遇到使用WebForm 并且实现AJAX的需求:
现在提供两种方法来实现aspx页面通过ajax调用aspx后台的方法。
1 是 引用webservrice 并且使用静态方法
后台代码:
using System.Web.Services; //WebMethod 依赖于此引用 [WebMethod] public static int Add(int num1, int num2) { return num1 + num2; }
前台调用:
<script src="Scripts/jquery-1.10.2.min.js"></script> //引入jquery
function add(a, b) {
$.ajax({
url: "WebFprmAjax.aspx/Add",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
num1: a,
num2: b
}),
success: function (data) {
alert(data.d)
}
})
}
2 是 手工输出请求流的形式
后台代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(this.Request.Form["type"]) && (this.Request.Form["type"] == "ajax"))
{
this.DoCallback();
}
}
//根据不同的action 确认需要调用的是哪一个方法,并输出返回结果
private void DoCallback()
{
string action = this.Request.Form["Action"];
this.Response.Clear();
this.Response.ContentType = "application/json";
string writeText = string.Empty;
switch (action)
{
case "Subtraction":
writeText = Subtraction();
break;
}
this.Response.Write(writeText);
this.Response.End();
}
//实际负责计算的方法
private string Subtraction()
{
int a = int.Parse(this.Request.Form["num1"]);
int b = int.Parse(this.Request.Form["num1"]);
var result = new
{
statue = true,
msg = a + b
};
//使用Newtonsoft来序列化一个匿名对象,从而实现转化为json返回格式
return Newtonsoft.Json.JsonConvert.SerializeObject(result);
}
前台调用:
function sub(a,b)
{
$.ajax({
url: "WebFprmAjax.aspx?v=" + new Date().getTime(), //防止被浏览器缓存
type: 'POST',
dataType: 'json',
timeout: 10000,
data: {
Action: "Subtraction", //调用方法名
type: "ajax", //自定义标识判断ajax方法
num1: a, num2: b //提交的数据
} ,
//contentType: "application/json; charset=utf-8", //不能使用接送 会造成request.form 无法获取到对应参数
success: function (data) {
if (data.statue) {
alert(data.msg)
}
else {
alert("系统忙请稍后再试!");
}
}
});
}
以上是在webForm页面ajax调用自身后台页面的两种方式,各有其优点,当然ajax调用后台远远不止这两种方式,还有更多的欢迎分享