我创建了一个应用程序,以便它可以使用AngularJS HTTP Get方法读取JSON文件数据,但我没有按预期在表中获得结果。 以下是代码:
的HomeController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CategoryWebApplication.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
}
视图:Index.cshtml
<html>
<head>
<title>Angular JS Includes</title>
<style>
table, th, td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h2>Sample Category Application</h2>
<div ng-app="" ng-controller="categoryController">
<table>
<tr>
<th>Category ID</th>
<th>Category Name</th>
</tr>
<tr ng-repeat="category in categories">
<td>{{ category.CategoryID }}</td>
<td>{{ category.CategoryName }}</td>
</tr>
</table>
</div>
<script>
function categoryController($scope, $http) {
var url = "http://localhost:4425/Category.txt";
$http.get(url).success(function (response) {
$scope.categories = response;
});
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"> </script>
</body>
</html>
文本文件类别中的JSON如下: 的 Category.txt
[
{
"CategoryID" : 1,
"CategoryName" : "Blood"
},
{
"CategoryID" : 2,
"CategoryName" : "Urine"
},
{
"CategoryID" : 3,
"CategoryName" : "Saliva"
},
{
"CategoryID" : 4,
"CategoryName" : "Serum"
},
{
"CategoryID" : 5,
"CategoryName" : "Hair"
},
{
"CategoryID" : 6,
"CategoryName" : "Nail"
},
{
"CategoryID" : 7,
"CategoryName" : "Tissue"
}
]
以下是我在浏览器中获得的结果
答案 0 :(得分:1)
我遇到了类似的麻烦,服务器正确发送了json数据但是角度没有正确读取它。经过几个小时的研究后,JSON.parse()爆炸了,它就像一个魅力。更多参考:https://www.w3schools.com/js/js_json_parse.asp