aspx使用Ajax请求后端的两种方法

第一种:直接请求后端方法

后端代码

后端方法一定要是公共的、静态的,并且返回类型为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);
                    }
                })

参考链接:
https://www.cnblogs.com/luoyeluoy/p/6021456.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值