zoukankan      html  css  js  c++  java
  • angular Jsonp的坑

      angular 为了解决跨域问题 一些第三方接口会提供jsonp来调用,需要使用callback=JSON_CALLBACK来处理 

      这个时候问题来了,有些借口是不支持callback里面带有点语法的,最典型的就是豆瓣了,而callback=JSON_CALLBACK 会被 angular转换成 callback = angular.callbacks._[id]这种形式,

      这个时候就会报错了,因为返回的是json格式而不是jsonp格式。为了解决这类问题最简单的方法肯定是重定义方法名,我在这里就是采用这种方法的,但是我们应该怎么改名字呢?答案就是在http拦截器里面,详情看代码。  

    https://api.douban.com/v2/book/isbn/' + isbn + "/reviews?callback=JSON_CALLBACK"
      .factory("httpInterceptor", ["App", "$rootScope", '$injector','$timeout', function (App, $rootScope, $injector,$timeout) {return {
                request: function (config) {
                    if (config.method === 'JSONP') {
                        console.log(config);
                        var callbackId = angular.callbacks.counter.toString(36);
                        config.callbackName = 'angular_callbacks_' + callbackId;
                        config.url = config.url.replace('JSON_CALLBACK', config.callbackName);
    
                        $timeout(function () {
                            window[config.callbackName] = angular.callbacks['_' + callbackId];
                        }, 0, false);
                    }
                    if (!config.isLoading) {
                        count++;
                        $rootScope.$broadcast('loading:show')
                    }
                    return config || App.q.when(config);
                },
                requestError: function (rejection) {               return App.q.reject(rejection)
                },
                response: function (response) {
                   return response || App.q.when(response);
                },
                responseError: function (rejection) {// do something on response error
                    return App.q.reject(rejection);
                }
            }
        }])

      就是以上代码进行方法名更改了。

      以上思路来源于 http://stackoverflow.com/questions/25400891/how-to-custom-set-angularjs-jsonp-callback-name

  • 相关阅读:
    LOJ#6031. 「雅礼集训 2017 Day1」字符串
    LG P4768 [NOI2018] 归程
    LG P3250 [HNOI2016]网络
    BZOJ4644 经典傻逼题
    LG P4373 [USACO18OPEN]Train Tracking P
    CF1375H Set Merging
    LG P6541 [WC2018]即时战略
    CF1097G Vladislav and a Great Legend
    python学习笔记-基本概念
    python学习笔记十-文件操作
  • 原文地址:https://www.cnblogs.com/HeJason/p/5604835.html
Copyright © 2011-2022 走看看