谁能指导我如何从asp.net web方法获取json数据,并在angularJS中使用它。
app.controller('MainController', ['$scope', function ($scope, $http) { try { $http({ method: 'GET', url: 'ProblemList.aspx/GetProblemList' }) .success(function (data, status, headers, config) { alert(data); }).error(function (data, status, headers, config) { }); } catch (e) { throw e; }
我遇到了同样的问题,我尝试了许多不同的方法,这是我发现它起作用的方法…(我认为技巧是标头配置和带有“ data:{}”的json参数的组合,我是不确定,但这确实很棘手)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestAngular.aspx.cs" Inherits="COEWebApp.NCoe.Employees.TestAngular" %> <!DOCTYPE html> <html lang="en"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script> </head> <body ng-app="myapp"> <div ng-controller="MyController" > <button ng-click="myData.doClick(item, $event)">Send AJAX Request</button> <br/> Data from server: {{myData.fromServer}} </div> <script> angular.module("myapp", []) .controller("MyController", function ($scope, $http) { $scope.myData = {}; $scope.myData.doClick = function (item, event) { $http.post('TestAngular.aspx/GetEmployees', { data: {} }) .success(function (data, status, headers, config) { $scope.myData.fromServer = data.d; }) .error(function (data, status, headers, config) { $scope.status = status; }); } }).config(function ($httpProvider) { $httpProvider.defaults.headers.post = {}; $httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8"; }); </script> </body> </html>
在隐藏代码的同一aspx页面上,这是简单的代码…
[WebMethod] public static string GetEmployees() { return "OK-test"; }