我正在学习 Angular.js,今天是我的第二天。下面是一个简单的函数
var XApp = angular.module("XApp", ['ngResource']);
XApp.controller('MenuParentController', function ($scope, $http) {
$http.get('api/menu?type=json').success(function (data) {
console.log('Inside MenuParentController ' + JSON.parse(data));
$scope.parentItems = JSON.parse(data);
});
})
以下是 console.log 的输出:
Inside MenuParentController [{"NodeId":261,"ParentId":9,"NodeName":"Clothing"},{"NodeId":262,"ParentId":9,"NodeName":"Jewellery"},{"NodeId":263,"ParentId":9,"NodeName":"Bags"},{"NodeId":12,"ParentId":1,"NodeName":"Home Décor"},{"NodeId":10,"ParentId":1,"NodeName":"Stationery & Office Supplies"},{"NodeId":811,"ParentId":1,"NodeName":"Gifts"}]
这是我得到的错误:
Error: [ngRepeat:dupes] http://errors.angularjs.org/1.2.14/ngRepeat/dupes?p0=item%20in%20parentItems&p1=string%3Ad
执行 JSON.parse(data)[0]
给出 [
作为输出,这是错误的。相反,它应该是 {"NodeId":261,"ParentId":9,"NodeName":"Clothing"}
HTML:
<li data-ng-repeat="item in parentItems"><a href="/{{ item.NodeId }}/{{ item.NodeName }}" title="{{ item.NodeName }}" class="newMenuClass {{item.NodeName | lowercase }}">{{ item.NodeName }}</a></li>
不知何故,Angular 将 JSON 对象的每个字符视为该对象的属性。知道为什么吗?
编辑:
当我使用 $.ajax 时一切正常
$.ajax({
url: 'api/menu?type=json',
dataType: 'json',
async: false,
success: function (data) {
console.log('Inside MenuParentController ' + data);
$scope.parentItems = JSON.parse(data);
}
});
编辑 2:
当我点击http://localhost:57086/api/menu?type=json
时,这是我得到的输出
"[{\"NodeId\":261,\"ParentId\":9,\"NodeName\":\"Clothing\"},{\"NodeId\":262,\"ParentId\":9,\"NodeName\":\"Jewellery\"},{\"NodeId\":263,\"ParentId\":9,\"NodeName\":\"Bags\"},{\"NodeId\":12,\"ParentId\":1,\"NodeName\":\"Home Décor\"},{\"NodeId\":10,\"ParentId\":1,\"NodeName\":\"Stationery & Office Supplies\"},{\"NodeId\":811,\"ParentId\":1,\"NodeName\":\"Gifts\"}]"
最佳答案
那就对了。
错误在于将数据序列化两次,导致生成包含实际 JSON 数据的单个字符串。
$.ajax
和 dataType: 'json'
在将数据传递给 success
回调之前隐式反序列化数据。这就是为什么 JSON.parse
调用(第二次反序列化运行)成功的原因。
关于javascript - $http.get 返回格式错误的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22452488/