I have been tring to make a ajax request but there seems to be a problem. When my json attributes names are in " ( like {"name":value"} ), it works but when attribute names are not. I have following excepiton
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
Here is my code:
index.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;
});
};
data.json
{
success : "true",
data: [{name:"val"}]
}
You must wrap attribute names in "
. This is the only way to specify valid transport JSON, which is stricter than object notation in an executable JavaScript context. Any JSON parser will fail if you try to use the more lax notation.
See also the spec for JSON which mandates this.
Even I had the similar issue and the solution is, your string data should be in a specific format for JSON.parse or angular.fromJson to work.
For ex:
var myString = '{"name":"nomad"}';
console.log(JSON.parse(myString));
The console output is: Object {name: "nomad"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With