AngularJS http.jsonp回调未定义



我正在尝试从控制器内部检索jsonp数据。我想从$http.jsonp内的url中获取一些jsonp数据,并将其传递给一个成功函数,该函数循环遍历数据,然后将其推送到变量dataxx中,但我一直收到这个错误:

未捕获引用错误:myJsonMethod未定义

 angular.module('app',  ['onsen'])
    .controller('ChartController', ['$scope', '$http', function($scope,$http) {
      this.data = [{
        key: 'Data',
        values: []
      }];
      $http.jsonp("https://demo8162910.mockable.io/json?callback=myJsonMethod").
            success(function(data, status, headers, config) {
                //what do I do here?
                dataxx.push({"x":9,"y":11},{"x":9,"y":18});
            }).
            error(function(data, status, headers, config) {
                $scope.error = true;
            }); 
      $scope.data = [{
            key: 'Data',
            values: dataxx
        }];       
    }])
    .factory('d3', [function() {
      return d3;
    }])
    .factory('nv', [function() {
      return nv;
    }])
    .directive('lineChart', ['d3', 'nv', function(d3, nv) {
      return {
        restrict: 'E',
        scope: {
          data: '=',
          height: '@',
          width: '@'
        },
        template: '<svg ng-attr-height="{{ height }}" ng-attr-width="{{ width }}"></svg>',
        link: function(scope, element) {
          var svg = element.find('svg'),
            chart;
          var update = function() {
            d3.select(svg[0])
              .datum(scope.data)
              .call(chart);
          };
          scope.$watch(function() { return angular.toJson(scope.data); }, function() {
            if (chart) {
              update();
            }
          });
          scope.$on('chartloaded', update);
          nv.addGraph(function() {
            chart = nv.models.lineChart()
              .showLegend(false)
              .showYAxis(true)
              .showXAxis(true);
            chart.xAxis
              .axisLabel('x')
              .tickFormat(d3.format('.2f'));
            chart.yAxis
              .axisLabel('y')
              .tickFormat(d3.format('.2f'));
            nv.utils.windowResize(function() {
              chart.update()
            });
            scope.$emit('chartloaded');
            return chart;
          });
        }
      }
    }]);

引用documentation中传递给jsonp方法的url参数:

指定请求目的地的相对或绝对URL。回调的名称应该是字符串JSON_callback。

因此:

https://demo8162910.mockable.io/json?callback=JSON_CALLBACK

或者,如果你想使用myJsonMethod,请确保你已经定义了这样的函数,它将被调用:

function myJsonMethod(result) {
    ... 
}

在您的案例中,您使用了标准的.success回调,该回调将在内部定义一个名为JSON_CALLBACK的函数。

不幸的是,从我所看到的情况来看,这个远程端点完全忽略了callback查询字符串参数。以下URL都返回相同的结果,这当然是错误的:

  • https://demo8162910.mockable.io/json
  • https://demo8162910.mockable.io/json?callback=foo_bar
  • https://demo8162910.mockable.io/json?callback=JSON_CALLBACK

因此,我建议您与已经实现此API的开发人员交谈,并要求他们尽可能不要硬编码回调名称,而是尊重查询字符串参数。

如果由于某种原因无法修复这个API,那么您唯一的机会就是定义一个名为myJsonMethod的函数,正如我前面所展示的那样。

最新更新