angularjs – 拒绝从’*’执行脚本,因为它的MIME类型(‘applicat
我是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 现在,当我访问’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' }); }]); 我在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> 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; }]); 当我访问’#/ phones’时,脚本模板中的文本也会显示.问题是 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. 2)在firefox中,显示以下错误. SyntaxError: missing ; before statement 谢谢您的帮助.
嘿所以我相信你的问题是你的rails控制器正在返回JSON而不是JSONP.您的控制器必须显式指定回调函数,该函数可由请求参数指定.
有关从rails控制器返回JSONP的示例,请参见Handling jsonp in rails 3 controller 所以你的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 那么对于角度方面,这个答案可以帮助你: 我认为你的角度看起来像: var appServices = angular.module('appServices',$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; }]); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |