第一种:直接请求后端方法
后端代码
后端方法一定要是公共的、静态的,并且返回类型为string,并且加上WebMethod特性
需要引用:System.Web.Services
代码如下
[WebMethod]
public static string GetInfo(string id)
return "";
}
前端代码
url是当前页面的完整名称加斜杠然后跟上需要请求的后端方法名称
data参数需要转换为json字符串
success和error方法返回的data参数,需要使用data.d获取,至于为什么data.d之前看过一篇博客,已经忘记
$.ajax({
url: 'SubjectInfo.aspx/GetInfo',
type: 'post',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
data: JSON.stringify({
id: $("#id").val()
}),
success: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.responseText);
}
})
第二种直接请求方法所在的页面
后端代码
直接使用ajax的post请求,使用this.Request.Form[“”]接收传输的参数
返回参数一定要使用Json对象转换的字符串,否则可能会出现请求异常问题
代码如下
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//直接通过页面ajax请求只能请求静态方法,所以此处直接通过指定参数post请求执行指定的方法
if (!string.IsNullOrWhiteSpace(this.Request.Form["type"]) && (this.Request.Form["type"] == "ajax"))
{
this.DoCallback();
}
}
}
//根据不同的action 确认需要调用的是哪一个方法,并输出返回结果
private void DoCallback()
{
string action = this.Request.Form["Action"];
string userName = this.Request.Form["userName"];
string pwd = this.Request.Form["pwd"];
string phoneOrEmail = this.Request.Form["phoneOrEmail"];
string checkCode = this.Request.Form["checkCode"];
this.Response.Clear();
this.Response.ContentType = "application/json;charset=utf-8";
string writeText = string.Empty;
switch (action)
{
case "Login":
writeText = Login(userName, pwd);
break;
case "CheckCodeLogin":
writeText = CheckCodeLogin(phoneOrEmail, checkCode);
break;
default:
writeText = GetRtnJson(false, "不存在的请求方法");
break;
}
Response.Write(writeText);
Response.End();
}
/// <summary>
/// 获取返回参数Json
/// </summary>
/// <param name="status"></param>
/// <param name="msg"></param>
/// <returns></returns>
private string GetRtnJson(bool status, string msg)
{
var result = new
{
status = status,
msg = msg
};
return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(result);
}
前端代码
请求时不需要contentType
后端返回的json字符串,返回参数data可直接使用值,无需进行json格式化
$.ajax({
url: 'Login.aspx?v=' + new Date().getTime(), //防止被浏览器缓存
type: 'POST',
//contentType: 'application/json; charset=utf-8', //不能使用接送 会造成request.form 无法获取到对应参数
dataType: 'json',
timeout: 10000,
data: {
Action: 'Login',
type: 'ajax',
userName: userName,
pwd: pwd
},
success: function (data) {
if (data.status) {
window.location.href = "../Index.aspx";
}
else {
alert(data.msg);
}
},
error: function (data) {
alert(data.responseText);
}
})