码迷,mamicode.com
首页 > Web开发 > 详细

Angular中的jsonp

时间:2016-12-29 23:01:04      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:地址   src   .com   api   异步请求   amp   rip   pen   log   

1、一般我们使用Angualr中的jsonp值这样使用的:注入$http服务
这样使用jsonp的方式可以支持多数api,但是douban不支持无法使用
 1 module.controller(‘InTheatersController‘,[‘$scope‘,‘$http‘, function($scope,$http){
 2  4 var doubanApiAddress = ‘https://api.douban.com/v2/movie/in_theaters‘;
 5 
 6 /!*在angualr中使用jsonp服务必须在的当前地址后面加
 7 * 一个参数callback(此名不固定)=‘JSON_CALLBACK‘,angular会将此替换为一个随机函数名 * *!/
 8 
 9 $http.jsonp(doubanApiAddress+‘?callback=JSON_CALLBACK‘).then(function(res){
10 console.log(res);
11 if(res.status === 200){
12 $scope.subjects = res.data.subjects;
13 }else{
14 $scope.message = ‘哎呀,获取数据失败了!‘+res.statusText;
15 }
16 },function(err){
17 $scope.message = ‘哎呀,获取数据失败了2!‘+err.statusText;
18 })
19 }]);

于是我们要自己写一个jsonp放服务来取代Angular中的jsonp服务

 1 /*
 2 在这个组件中写一个方便跨域的服务,方便其他模块也使用
 3 
 4 因为默认angualr提供的异步请求对象不支持自定义函数名
 5  而angular随机分配的回调函数douban不支持
 6 */
 7 
 8 ‘use strict‘;
 9 (function(angular){
10 
11     var http = angular.module(‘myApp.services.http‘,[]);
12 
13     http.service(‘HttpService‘,[‘$window‘,‘$document‘,function($window,$document){
14 
15         //url:https://api.douban.com/v2/movie/in_theaters放在<script>中再放在html中
16         this.jsonp = function(url, data, callback){
17             //1、处理url地址中的回调参数
18             //2、创建一个script标签
19             //3、挂载回调函数,放在全局作用域中让回调的时候执行
20             //4、将script放在html中
21 
22             var cbFuncName = ‘my_json_cb_‘ + Math.random().toString().replace(‘.‘, ‘‘);
23             // 不推荐,我们推荐angular的方式
24             $window[cbFuncName] = callback;//$window就是window对象
25 
26             var querystring = url.indexOf(‘?‘) == -1 ? ‘?‘ : ‘&‘;
27             for (var key in data) {
28                 querystring += key + ‘=‘ + data[key] + ‘&‘;
29             }
30 
31             querystring += ‘callback=‘ + cbFuncName;
32 
33             //document对象是$document对象的数组成员
34             var scriptElement = $document[0].createElement(‘script‘);
35             scriptElement.src = url + querystring;
36             $document[0].body.appendChild(scriptElement);
37         }
38         //$window.$jsonp = jsonp;
39     }])
40 })(angular)

这样我们在模块中依赖myApp.services.http,并且注入HttpService服务就可以使用了



 

Angular中的jsonp

标签:地址   src   .com   api   异步请求   amp   rip   pen   log   

原文地址:http://www.cnblogs.com/beyonded/p/6234904.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!