【发布时间】:2017-06-07 04:50:28
【问题描述】:
我在HomeController下有如下Controller方法,
[HttpGet]
public ActionResult GetStudents()
{
Student std1 = new Student();
List<Student> stdlst = new List<Student>();
std1.Id = 1;
std1.Name = "Emmanuvel";
std1.Age = 25;
stdlst.Add(std1);
Student std2 = new Student();
std2.Id = 2;
std2.Name = "Michael";
std2.Age = 24;
stdlst.Add(std2);
Student std3 = new Student();
std3.Id = 3;
std3.Name = "Hannah";
std3.Age = 22;
stdlst.Add(std3);
return Json(stdlst, JsonRequestBehavior.AllowGet);
}
我正在使用下面的 Angularjs Ajax 函数调用此方法,
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
$scope.ButtonClick = function () {
$http.get('@Url.Action("GetStudents","Home")')
.success(function (data) {
$scope.students = data;
console.log($scope.students);
})
.error(function (data) {
console.log(data);
});
}
});
</script>
不幸的是,console.log 打印了查看页面的 HTML 代码,而不是 JSON 数据。这是 console.log 的输出,
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<div ng-app="MyApp" ng-controller="MyController">
<input type="button" value="Submit" ng-click="ButtonClick()"/>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
$scope.ButtonClick = function () {
$http.get('/Home/GetStudents')
.success(function (data) {
$scope.students = data;
console.log($scope.students);
})
.error(function (data) {
console.log(data);
});
}
});
</script>
</body>
</html>
帮助我理解我在这段代码中所做的错误。
【问题讨论】:
-
HTML 代码中的是是什么?它可能是一个异常页面,而不是实际结果吗?例如,如果您的@Url.Action() 没有得到处理,服务器将返回某种
route not found,它将出现在HTML 的开发人员“帮助”页面中......只是一个想法 -
我在html中只有一个按钮来调用Ajax函数,控制台日志返回那个html代码,我更新了打印什么日志的问题。
-
将您的操作方法签名从 ActionResult 更改为 JsonResult,以明确。另外,你不是在使用区域吗?
-
如果我将@Html.Action("GetStudents", "Home") 放在html代码中,它将返回json数据以及完整的html,烦人:(
-
可能会在触发此调用时检查浏览器发出的 http 请求(例如,在 Chrome 的“网络”选项卡中)。如果它以某种方式调用了错误的 URL,那么任何用于提供 JSON 的东西都可能是在为您的应用程序的索引页面提供服务,而不是返回错误代码。
标签: javascript angularjs json ajax asp.net-mvc