我注意到AngularJS需要来自后端服务器的javascript结果。
示例中的当前服务器返回带有javascript标头的angular.callbacks._0({"key": "value"});
。如何在Rails上以相同的格式返回?谢谢!
AngularJS默认情况下会根据该请求生成http://echo.jsontest.com/key/value?callback=angular.callbacks._0
个链接
以下是我的工作示例:
<!DOCTYPE html>
<html ng-app="Simple">
<body>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.min.js"></script>
<div ng-controller="SimpleController">
{{some_item.key}}
</div>
<script>
angular.module('Simple', ['ngResource']);
function SimpleController($scope, $resource) {
$scope.simple = $resource('http://echo.jsontest.com/key/value',
{callback:'JSON_CALLBACK'},
{get:{method:'JSONP'}}
);
$scope.some_item = $scope.simple.get();
console.log($scope.some_item.key);
}
</script>
</body>
</html>
答案 0 :(得分:1)
只要你有一个RESTful控制器响应JSON它就可以正常工作。
class ArticlesController < ApplicationController
respond_to :json
def index
articles = Article.all
respond_with articles
end
def get
article = Article.find(params[:id])
respond_with article
end
# etc.
end
您可以使用respond_with article, include: {:id, :title, :description}