asp.net ajax使用C#后台代码(无参数)

来源:互联网 发布:山姆.维特维奇 知乎 编辑:程序博客网 时间:2024/06/09 03:57

1、首先附上C#后台函数代码

[WebMethod]
    public static  int httest()
    {
        _Default temp = new _Default();


        return temp.dom();
        //Response.Write("<script>alert('调用成功!')</script>"); 
    }

注:[WebMethod]使用using System.Web.Services;  

必须包含[WebMethod]且是静态方法

public int dom() { 
    
        Random temp=new Random();


        return temp.Next(0, 100);
    }

因为dom是非静态成员函数,所以需要实例化一下 _Default类 ,这个类是你自己定义的类

2、ajax代码

 function testGet() {
             $.ajax({
                 type: "post", //要用post方式                 
                 url: "Default.aspx/httest",//方法所在页面和方法名
                 contentType: "application/json; charset=utf-8",
                 async: false,
                 dataType: "json",
                 success: function (data) {
                     // console.log(data.d);//返回的数据用data.d获取内容
                    num=data.d;
                 },
                 error: function (err) {
                     alert(err);
                 }
             });
             return num;
         }

3、因为我使用的是默认页的路径,所以要在APP_CODE文件夹中的RouteConfig.cs中将 settings.AutoRedirectMode = RedirectMode.Permanent;注释掉

4、完成ajax调用C#后台成员方法



原创粉丝点击