使用$ http获取JSON数据

时间:2015-08-10 13:23:00

标签: javascript json angularjs http angular-http

我正在尝试使用$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

3 个答案:

答案 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>

Working Plunkr

答案 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");
});