AngularJS意外字符串

时间:2015-11-10 01:46:48

标签: javascript angularjs http

遵循Angular书中的示例,它们具有以下代码:

<script>
   var test = {};


   var app = angular.module("app",[]);

   app.run(function($http){
      $http.get("/file").success(function(data){
         test.input = data;
      });
   });

   app.controller("ctrl",function($scope){
      $scope.handle = test;
   });


</script>

假设数据是从文件中提取的,然后推送到对象&#39; test&#39;然后将其放入范围的句柄变量中。然而,当我写这个时,问题是$ http.get:

   app.run(function($http){
      $http.get("/file").success(function(data){
         test = data;
      });
   });

产生以下错误:

  

SyntaxError:意外的字符串       at Object.parse(native)       在vc(http://localhost/common/js/frameworks/angular.min.js:15:480)       在Zb(http://localhost/common/js/frameworks/angular.min.js:82:229)       在http://localhost/common/js/frameworks/angular.min.js:83:143       在m(http://localhost/common/js/frameworks/angular.min.js:7:322)       在dd(http://localhost/common/js/frameworks/angular.min.js:83:125)       在d(http://localhost/common/js/frameworks/angular.min.js:84:380)       在http://localhost/common/js/frameworks/angular.min.js:119:113       at n.a. $ get.n. $ eval(http://localhost/common/js/frameworks/angular.min.js:133:221)       at n.a. $ get.n. $ digest(http://localhost/common/js/frameworks/angular.min.js:130:233
  (匿名函数)b。$ get(匿名函数)
  a。$ get.n. $ eval a。$ get.n. $ digest a。$ get.n. $ apply h K
  z.onload

对我来说,表示$ http不期待字符串url。有人可以向我解释一下吗?该书的示例代码是错误的,还是可能已过时?

编辑:

/ file内容如下:

  

[{&#34;&#34;:&#34; 1&#34;&#34; B&#34;:&#34; 2&#34;},{&#34; AA&#34 ;:&#34; 3&#34;&#34; BB&#34;:&#34; 4&#34;}]

编辑2:

从其他SO文章Problems parsing a JSON response using AngularJS看来,$ http.get似乎是自动解析

1 个答案:

答案 0 :(得分:2)

你应该对数据进行编码。并且错误将消失:

'[{"a":"1","b":"2"},{"aa":"3","bb":"4"}]'