带有JSON的Angular.js不起作用

Angular.js with JSON not working?

本文关键字:js 不起作用 Angular JSON 带有      更新时间:2023-09-26

我想知道你是否能帮我。我一直在尝试让JSON与Angular.js一起工作,但我在JSON$http.get()调用的细节方面遇到了困难。我只想让每个人的名字显示在网页的"人"标题下,但我的JSON调用不起作用。我知道这可能是一个愚蠢的小语法错误,但我似乎找不到。感谢所有帮助。这是我的代码:

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html ng-app='People'>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.4/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<title>People Webpage</title>
</head>
<body>
<h3>People</h3>
<div ng-controller='PeopleController as peeps'>
<div ng-repeat='person in peeps.people'>
<h5>{{person.name}}</h5>
</div>
</div>
</body>
</html>

JSON:

{
{ 'name' : 'Jack', 'age' : '28', 'weight' : '75kg'},
{ 'name' : 'Jill', 'age' : '25', 'weight' : '66kg'}
}

JAVASCRIPT:

var app = angular.module('People',[]);
app.controller('PeopleController',[ '$http' ,function($http){
    var names = this;
    names.people = [];
    $http.get('people.json').success(function(data){
        names.people = data;

    });
}]);

我尝试了警报(数据);在成功回调中,我收到的JSON如下:

"{{ 'name' : 'Jack', 'age' : '28', 'weight' : '75kg'},{ 'name' : 'Jill', 'age' : '25', 'weight' : '66kg'}}"

但是,如果尝试对创建的JavaScript对象调用警报,如下所示:

 var people = [
{ 'name' : 'Jack', 'age' : '28', 'weight' : '75kg'},
{ 'name' : 'Jill', 'age' : '25', 'weight' : '66kg'}
];
alert(people);

我收到了大意为:

{{ object : Object,  object : Object,  object : Object},
{ object : Object, object : Object, object : Object}}

这与我的问题有关吗?

JSON应该如何:

{
"people": [
    {
        "name": "Jack",
        "age": "28",
        "weight": "75kg"
    },
    {
        "name": "Jill",
        "age": "25",
        "weight": "66kg"
    }
]
}

您的通话方式:

$http.get('people.json').success(function(data){
    names.people = data.people;

});

你在$http.get中使用的成功方法是我通常不会做的,所以你要么查看data.people,要么查看data.data.people,这取决于你从电话中收到的响应。

console.dir(data) 

会让你好好看看收到的回复。

Ok希望其他人能写这篇文章,但:

将其用作JSON

[
    { 'name' : 'Jack', 'age' : '28', 'weight' : '75kg'},
    { 'name' : 'Jill', 'age' : '25', 'weight' : '66kg'}
]

在玩了我的JSON之后,我意识到错误是什么,感谢大家的帮助。

[
    {
        "name": "Jack",
        "age": "28",
        "weight": "75kg"
    },
    {
        "name": "Jill",
        "age": "25",
        "weight": "66kg"
    }
]

问题是,我首先使用{}作为外部封装,而不是[],感谢所有提出这一建议的人。此外,JSON需要双引号",而不是单引号"。特别感谢Likwid_T与我聊天并试图提供帮助,我真的很感激。