7

我一直在尝试发出 ajax 请求,但似乎有问题。当我的 json 属性名称在 " (例如 {"name":value"} )中时,它可以工作,但是当属性名称不是时。我有以下异常

SyntaxError: Unexpected token s
at Object.parse (native)
at pb (http://localhost:8080/angularjs/lib/angular.min.js:12:472)
at Vc.d.defaults.transformResponse (http://localhost:8080/angularjs/lib/angular.min.js:92:314)
at http://localhost:8080/angularjs/lib/angular.min.js:92:127
at Array.forEach (native)
at n (http://localhost:8080/angularjs/lib/angular.min.js:6:192)
at Qb (http://localhost:8080/angularjs/lib/angular.min.js:92:109)
at c (http://localhost:8080/angularjs/lib/angular.min.js:93:295)
at h (http://localhost:8080/angularjs/lib/angular.min.js:77:437)
at http://localhost:8080/angularjs/lib/angular.min.js:78:169 

这是我的代码:

索引.html:

<!doctype html>
<html ng-app>
<head>
<script src="lib/angular.min.js"></script>
<script src="js/indexApp.js"></script>
</head>
<body>
    <div>
        <div ng-controller="AjaxController">
            {{users.data}}
        </div>
    </div>
</body>
</html>

indexApp.js

function AjaxController($scope, $http) {
$scope.beers = [ 0, 1, 2, 3, 4, 5, 6 ];
console.log("OMW");
$http({
    method : 'GET',
    url : 'data.json'
}).success(function(data, status, headers, config) {
    $scope.users = data;
}).error(function(data, status, headers, config) {
    $scope.users = "error" + data;
});

};

数据.json

{
    success : "true",
    data: [{name:"val"}]
}
4

4 回答 4

18

必须将属性名称包装在". 这是指定有效传输 JSON 的唯一方法,它比可执行 JavaScript 上下文中的对象表示法更严格。如果您尝试使用更宽松的表示法,任何 JSON 解析器都会失败。

另请参阅强制执行此操作的 JSON 规范。

于 2013-05-03T09:27:22.240 回答
8

即使我遇到了类似的问题,解决方案是,您的字符串数据应该采用JSON.parseangular.fromJson工作的特定格式。

例如:

var myString = '{"name":"nomad"}';
console.log(JSON.parse(myString));

控制台输出为: Object {name: "nomad"}

于 2014-02-06T05:07:15.080 回答
1

我有同样的错误。其中一个 firstName 是这样的空字符串。 {"firstName":"", "lastName":"Doe"} 编辑:此错误也可能意味着您的 json 文件中主要存在一些语法错误。例如,注释掉 json 文件中的某些内容,或者在分隔两个键值对的逗号之间不留空格也会引发相同的错误。非常初学者的错误认为这会对其他人有所帮助。

于 2016-02-10T21:16:01.647 回答
0

就我而言,它返回以下错误:

SyntaxError:意外的令牌'

在 Object.parse (本机)

在 fromJson ( http://www.example.com/bower_components/angular/angular.js:1072:14 )

所以我们发现 Angular 内部发生的情况如下:

JSON.parse("{'error': 'message'}"); // error

实际上它返回了一个解析器错误,因为它期望 JSON 包含用 包裹的字符串"正如接受的答案所指出的那样

因此,我们只是修复了服务器响应以符合JSON 字符串规范

JSON.parse('{"error": "message"}'); // works!
于 2016-01-28T17:09:57.063 回答