asp.net 前后端调用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010673842/article/details/80749713


1前台调用后台(利用jquery)

 $.ajax({
                        type: "POST",  //请求方式
                        url: "ModelCenter.aspx/ToLogin",  //请求路径:页面/方法名字
                        data: {key:value},     //参数
                        dataType: "text",
                        contentType: "application/json; charset=utf-8",
                        success: function (msg) {  //成功
                            //alert("登录sucess");
                            var d = JSON.parse(JSON.parse(msg)["d"]);
                            if(d["code"] == '0')
                            {
                                //失败
                                alert("登录失败");
                            }
                            else if(d["code"] == 1)
                            {
                                //成功
                                alert("登录成功");
                            }
                            else
                            {
                                //异常
                                alert("登录异常");
                            }
                            
                        },
                        error: function (obj, msg, e) {   //错误
                            alert("网络错误");
                        }
                    });

利用POST方式调用页面 behind 中的 ToLogin 方法,需要传递的参数以字典的形式编辑,成功和失败会调用对应程序块,并返回msg信息,msg是一个jsonstring,使用 Json 解析后 key = 'd',就是后台程序返回给我们的值.

与之配套的后台程序

        [System.Web.Services.WebMethod]
        public static string ToLogin(string userid ,string pwd)
        {

            //做一些处理

            Dictionary<string, string> cbdict = new Dictionary<string, string>();
            cbdict.Add("code", "1"); 
            cbdict.Add("username,"");
            cbdict.Add("roles", "");


            return JsonConvert.SerializeObject(cbdict);

        }

后台函数注意点

1.中括号内声明,2.static string ,3.Tologin对用的参数和传递的参数名称数目对应,4.return 返回的字符串 就是前台获取的key = "d" 对应的字符串.


后台调用前台,推荐一种写法

                ClientScript.RegisterStartupScript(this.GetType(), "", " <script>Alert('Hi');</script>");
需要变动的就是<script>块之间的 js 内容









猜你喜欢

转载自blog.csdn.net/u010673842/article/details/80749713
今日推荐