ASP.NET WebMethod方法使用 、AngularJS $http请求、 Jquery $.ajax请求

前台页面为 test.aspx页面
// 使用PageMethod方法,必须先引入ScriptManager 控件 <asp:ScriptManager ID="scriptManager1" runat="server"></asp:ScriptManager>
//后台页面为: test.aspx.cs页面 //后台代码: [WebMethod(EnableSession = true)] public static string GetCardListByConId(string id){ ///处理、 返回数据 }

使用静态方法GetCardListByConId()几种方法:【前台JS】

1、使用PageMethods 方法直接调用

PageMethods.GetCardListByConId(id, function (data)( ///返回的 数据处理))} 

2、使用Jquery $.ajax()请求调用

  $(function () {
        var Cid = "<%=ConfirmationID %>";
        var JsonData = "{id: '" + Cid + "'}";
        console.log("URL: "  + window.location.href);
        $.ajax({
            type: "POST",
            url: "test.aspx/GetCardListByConId",
            data: "{}",        ///// 注意数据的格式 ,比如后台id为string,此处应该为  data:"{id:'AA14208'}" ,不同的数据格式要灵活运用
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                console.log("成功:" + msg.d);         /// msg.d 就是返回的数据
            },
            error: function (msg) {
                console.error("Error MSG : " + msg);
                console.error(msg.id);
            }
        });
    });

PS: 以上两种方法都无法和AngularJS 控制器中将放回值取出, 只能在回调函数中处理返回的数据,而不能将数据取出回调函数。   也可能是我没有找对方法,谁要有方法不妨告知一下。

3、使用AngularJS 的$http, $http.post() 方法,这样能和angularjs 结合使用, 将至取出回调函数。

 (1)、$http.post()方法

app.controller("CardList1", ["$scope", "$http", "$rootScope", function ($scope, $http, $rootScope) {
  $http.post("test.aspx/GetCardListByConId", "{id:''}").success(function (data) { alert(typeof (data)); /// data 是object alert(typeof (data.d)); /// data.d 是字符串string var dataJSON = JSON.parse(data.d); /// 解析为json对象 $scope.CardList = dataJSON; //一定要解析才能当做对象使用 , 这样返回的数据可以取出, 然后使用angularJS 运用到HTML中
}).error(function (data) { /// 错误请求处理 });
}

  (2)、$http方法

$http({
            method: "POST",
            url: "test.aspx/GetCardListByConId",     //// 请求,获取json
            data: "{id:''}",      /// 注意 不能使用get 方式
        }).then(
            function (response) {  // response 包括config,data,status等
                var Data = response.data.d;   //// 此时传递过来数据,是string ,
                alert(typeof (Data));
                var DataJson = JSON.parse(Data);  /// 将json字符串解析为json对象 
                alert(typeof(DataJson));
                $scope.CardList = DataJson;      /// 此处就可以
            },
            function (response) { alert(response); }
        );

 

posted @ 2016-10-24 16:48  jason_LSZ  阅读(501)  评论(0编辑  收藏  举报