pra*_*ase 8 jsonp http angularjs
我是AngularJS的新手.我正在使用rails应用程序以json格式公开数据.该数据将由角度应用程序使用.角度回购和铁路回购完全不同.不同存储库的原因是因为我希望我的rails repo只是使用我可以在角度应用程序中使用的API来公开数据.
我的rails控制器如下
class Api::V1::PhonesController < ApplicationController
def index
render json: Phone.all
end
def show
render json: Phone.find(params[:id])
end
...
end
Run Code Online (Sandbox Code Playgroud)
现在,当我访问'localhost:3000/api/v1/phones'时,它会返回所有手机的json数据.当我访问'localhost:3000/api/v1/phones/1'时,它返回id为1的手机的json数据.我使用http://jsonlint.com/验证了json数据格式.一切都很好,直到这里.
我的angularjs路由文件如下:
$routeProvider.
when('/phones', {
templateUrl: 'list.html',
controller: 'PhoneListController'
}).
when('/phones/:id', {
templateUrl: 'show.html',
controller: 'PhoneShowController'
}).
otherwise({
redirectTo: '/phones'
});
}]);
Run Code Online (Sandbox Code Playgroud)
我在angular repo中的index.html中嵌入了list.html模板.
<html ng-app='phoneCatApp'>
...
</html>
<script type="text/ng-template" id="list.html">
This is the list template.
</script>
Run Code Online (Sandbox Code Playgroud)
services.js的代码如下:
var appServices = angular.module('appServices', []);
phoneCatApp.factory('appServices', ['$http', '$q', function($http, $q){
var url = "http://localhost:3000/api/v1/";
//get all phones
this.getPhones = function(){
var defered = $q.defer();
var listApi = url + "phones";
$http.jsonp(listApi).then(function(results){
defered.resolve(results);
}, function(error){
defered.reject(error);
});
return defered.promise;
}
return this;
}]);
Run Code Online (Sandbox Code Playgroud)
当我访问'#/ phones'时,脚本模板中的文本也会显示.问题是1)在chrome中,当我检查页面时会显示以下错误.
Refused to execute script from 'http://localhost:3000/api/v1/phones' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.
Run Code Online (Sandbox Code Playgroud)
2)在firefox中,显示以下错误.
SyntaxError: missing ; before statement
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助.
嘿所以我相信你的问题是你的rails控制器正在返回JSON而不是JSONP.您的控制器必须显式指定回调函数,该函数可由请求参数指定.
有关从rails控制器返回JSONP的示例,请参阅处理rails 3控制器中的jsonp
所以你的rails代码看起来像(我的导轨非常生锈......):
class Api::V1::PhonesController < ApplicationController
def index
if params[:callback]
format.js { render :json => {:phones => Phone.all.to_json}, :callback => params[:callback] }
else
format.json { render json: {:phones => Phone.all.to_json}}
end
end
Run Code Online (Sandbox Code Playgroud)
然后对于角度方面,这个答案可以帮助你解决: 解析angular.js中的JSONP $ http.jsonp()响应
我认为你的棱角看起来像:
var appServices = angular.module('appServices', []);
phoneCatApp.factory('appServices', ['$http', '$q', function($http, $q){
var url = "http://localhost:3000/api/v1/";
//get all phones
this.getPhones = function(){
var defered = $q.defer();
var listApi = url + "phones?callback=JSON_CALLBACK";
$http.jsonp(listApi).then(function(results){
defered.resolve(results);
}, function(error){
defered.reject(error);
});
return defered.promise;
}
return this;
}]);
Run Code Online (Sandbox Code Playgroud)