本文介绍了如何自定义设置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 将 JSON_CALLBACK 替换为angular.callbacks._0"之类的内容,因此是不允许的.

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);
    }
  };
})

Plunker 示例: http://plnkr.co/edit/S5K46izpIxHat3gLqvu7?p=preview

希望这会有所帮助.

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

09-02 04:53