我正在尝试使用$http
函数获取JSON数据;我总是得到这个错误。这是我的HTML代码:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in code">
{{ x.code }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("data.json")
.success(function (response) {$scope.code = response;})
.error(function (response) {alert("Error")})
});
</script>
</body>
</html>
这是我的data.json文件:
{
"code":"#include <stdio.h>
int main()
{
printf('Hello world');
return 0;
}"
}
以下是plunker http://plnkr.co/edit/Q4dsCjHM3ykgp2SaHw35?p=preview
答案 0 :(得分:2)
您的JSON格式不正确。 string
代码行应该在一行上,例如,
{
"code": "#include <stdio.h> int main() ...."
}
您始终可以在jsonlint.com
验证您的JSON答案 1 :(得分:2)
请将您的数据更改为以下。基本上它应该是字符串,使用pre
标记表示换行符&amp;然后用\n
{
"code": "#include <stdio.h>\n int main()\n printf('Hello world');\n return 0;\n}"
}
<强> HTML 强>
<ul>
<li ng-repeat="x in code">
<pre>{{ x }}</pre>
</li>
</ul>
答案 2 :(得分:0)
您的JSON格式不正确。
<强> JSON 强>
{
"code":"#include <stdio.h>int main(){printf('Hello world');return 0;}"
}
然后,您可以访问请求中的code
字段:
<强>控制器强>
$http.get("data.json")
.success(function (response) {
$scope.code = response.code;
})
.error(function (response) {
alert("Error");
});