【Web】【Ajax】Ajax调用Aspx后台方法

来源:互联网 发布:淘宝无线展现词没有了 编辑:程序博客网 时间:2024/05/29 19:48

Ajax调用的前提(以aspx文件为例:)

1、首先需要在aspx文件后台中引用using System.Web.Services;

2、需要调用的方法必须是公共的(public)、静态的(static;如果不是会提示“500 Internal Server Error 问题”,代表找不到method。

3、方法定义需要加入[WebMethod]的声明

4、一般建议由返回类型,最起码可能知道调用成功不成功。


下面是简单的调用示例:

无参调用

后台方法

        [WebMethod]        public static string setAlert() {            return "1";        }

Ajax调用

        $.ajax({            url: "test.aspx/setAlert",   //调用路径及方法            type: "post",//提交方式            dataType: 'json',//数据传递类型            contentType: "application/json;charset=utf-8",//设置内容类型,即在页面中传递的方式及编码方式            success: function (data) {//如果成功,接收返回结果                alert(data.d);//输出返回结果,需要注意的是,更具不同数据类型,会存在不同的数据处理方式,这里使用的是单个字符串数据,可以直接使用,如果是多个,需要分别接受返回的数据            },            error: function (data) {                alert(false);//如果调用错误,则返回false            }        });


有参调用

后台方法

        [WebMethod]        public static string setAlert(string s)        {            return s+"123";        }

Ajax调用

        $.ajax({            url: "test.aspx/setAlert",   //调用路径及方法            type: "post",//提交方式            data:"{'s':'Dongle'}",//传递参数            dataType: 'json',//数据传递类型            contentType: "application/json;charset=utf-8",//设置内容类型,即在页面中传递的方式及编码方式            success: function (data) {//如果成功,接收返回结果                alert(data.d);//输出返回结果,需要注意的是,更具不同数据类型,会存在不同的数据处理方式,这里使用的是单个字符串数据,可以直接使用,如果是多个,需要分别接受返回的数据            },            error: function (data) {                alert(false);//如果调用错误,则返回false            }        });



0 0
原创粉丝点击