本文介绍了如何自定义设置angularjs jsonp回调名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须通过angularjs从某个网站获取json数据.我已经按照下面的链接正确地完成了所有操作.

I have to fetch json data from some website through angularjs. i have done everything correctly according to the link below.

我的问题是api不允许回调参数具有除字母,数字和_之外的任何字符.而且由于angular用'angular.callbacks._0'之类的东西替换了JSON_CALLBACK,所以不允许使用它.

My problem is the api does not allow callback parameter to have any character except letters, numbers and _. And since angular replaces the JSON_CALLBACK with something like 'angular.callbacks._0', its not being allowed.

如何自定义为angularjs设置此值?

How can i custom set this value for angularjs?

在angular.js中解析JSONP $ http.jsonp()响应

谢谢

推荐答案

回调名称在此处硬编码 httpBackend.js#L55 ,因此无法对其进行配置.

The callback names are hard-coded here httpBackend.js#L55, so you can't config it.

但是,您可以编写HTTP拦截器来解决该问题,如下所示:

But, you could write a HTTP interceptor to workaround it like this:

.factory('jsonpInterceptor', function($timeout, $window, $q) {
  return {
    'request': function(config) {
      if (config.method === 'JSONP') {
        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);
      }

      return config;
    },

    'response': function(response) {
      var config = response.config;
      if (config.method === 'JSONP') {
        delete $window[config.callbackName]; // cleanup
      }

      return response;
    },

    'responseError': function(rejection) {
      var config = rejection.config;
      if (config.method === 'JSONP') {
        delete $window[config.callbackName]; // cleanup
      }

      return $q.reject(rejection);
    }
  };
})

柱塞示例: http://plnkr.co/edit/S5K46izpIxHat3gLqvu7?p =预览

希望这会有所帮助.

这篇关于如何自定义设置angularjs jsonp回调名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:53