使用Angular' $ http时无法从控制器获取json信息

时间:2014-11-28 15:51:38

标签: javascript ruby-on-rails json angularjs

所以我试图从控制器中的动作中获取一些信息。

目前的行动如下:

def index
        @users = User.all

        respond_to do |format|
            format.html
            format.json { render json: @users }
        end
end

此索引页面设置为routes.rb

中的根目录

现在,这就是我的AngularJs控制器的样子,从我试图获取信息的位置:

@test.controller 'TestCtrl', ['$scope', '$location', '$http', ($scope, $location, $http) ->
    $scope.data = []

    $http.get('/')
    .success (data) =>
        $scope.data = data
        console.log($scope.data)
    .error (data) ->
        console.log('error!')
]

当我加载根页面时,我只在Javascript控制台日志中将整个页面加载为html。

所以我在这里遗漏了一些需要做的事情,以便在json中为我的AngularJs控制器响应动作index吗?

服务器日志:

Started GET "/" for 127.0.0.1 at 2014-11-28 18:02:26 +0200
Processing by VisitorsController#index as HTML
   (0.4ms)  SELECT COUNT(*) FROM "users"
  User Load (0.2ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1  ORDER BY "users"."id" ASC LIMIT 1
   (2.1ms)  SELECT COUNT(*) FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."followed_id" WHERE "relationships"."follower_id" = $1  [["follower_id", 1]]
   (0.2ms)  SELECT COUNT(*) FROM "users" INNER JOIN "relationships" ON "users"."id" = "relationships"."follower_id" WHERE "relationships"."followed_id" = $1  [["followed_id", 1]]
  Rendered users/_stats.html.erb (4.8ms)
  Rendered visitors/index.html.erb within layouts/application (6.9ms)
  Rendered layouts/_navigation_links.html.erb (0.3ms)
  Rendered layouts/_navigation.html.erb (0.7ms)
  Rendered layouts/_messages.html.erb (0.0ms)
Completed 200 OK in 137ms (Views: 134.0ms | ActiveRecord: 2.9ms)

1 个答案:

答案 0 :(得分:0)

我通过不对'/'路由进行查询而是向'/users.json'进行查询来解决问题。即使你做了这样的事情:'/.json',它也行不通。