【问题标题】:Getting error while fetching data from json file using Angular.js使用 Angular.js 从 json 文件中获取数据时出错
【发布时间】:2015-12-31 15:00:37
【问题描述】:

从我的 json 文件中获取数据时出现以下错误。

错误:

SyntaxError: Unexpected token '
    at Object.parse (native)
    at uc (http://localhost/json/angularjs.js:15:480)
    at Zb (http://localhost/json/angularjs.js:82:229)
    at http://localhost/json/angularjs.js:83:143
    at m (http://localhost/json/angularjs.js:7:322)
    at cd (http://localhost/json/angularjs.js:83:125)
    at d (http://localhost/json/angularjs.js:84:380)
    at http://localhost/json/angularjs.js:118:334
    at n.$eval (http://localhost/json/angularjs.js:132:452)
    at n.$digest (http://localhost/json/angularjs.js:129:4

这是我的代码:

var test=angular.module('testapp', []);
test.controller('HelloController',function ($scope,$http) {
    console.log('hello');

    $http({
         method: 'GET',
         url: 'data.json',
         headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
     }).then(function successCallback(response){

     },function errorCallback(response) {
        //$state.go('/',{}, { reload: true }); 
     });
  // Do something with myService
});

data.json:

[
{
    'id':1,
    'email':'abc@gmail.com',
    'name':'Rahul'
    },
    {
    'id':2,
    'email':'def@gmail.com',
    'name':'Ram'
    },
    {
    'id':3,
    'email':'ghi@gmail.com',
    'name':'praveen'
    }
]

如何获取所有数据?

【问题讨论】:

  • 尝试在 JSON 中使用双引号,",而不是单引号,'。
  • 我按照你的做了..仍然有错误。
  • 是同一个错误吗?正如@whistling_marmot 所指出的,第一个错误似乎是由于单引号引起的。尝试从 $http 调用中删除 headers 对象,因为您没有发布任何内容。
  • 是的错误是一样的。我认为它是一个路径错误。当我这样做时 /data.json 这个错误不会出现但无法获取正确的文件。当我再次这样做时 projectfoldername/data.json 再次错误的路径是也来了。

标签: javascript angularjs json


【解决方案1】:

Angular 代码没问题。问题出在 data.json 文件中,使用 " 而不是 '

data.json:

[
  {
    "id":1,
    "email":"abc@gmail.com",
    "name":"Rahul"
    },
    {
    "id":2,
    "email":"def@gmail.com",
    "name":"Ram"
    },
    {
    "id":3,
    "email":"ghi@gmail.com",
    "name":"praveen"
    }
]

可以看到http://plnkr.co/edit/LjrqDMolGoaQn96ds6fv?p=preview上运行的代码

【讨论】:

  • @whistling_marmot 已经在他对原始消息的评论中说过这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多