2015-12-31 33 views
1

我想從我的控制器裏面檢索jsonp數據。我要搶在$ http.jsonp從URL一些JSONP數據,並使之通過,通過數據環路成功的功能,然後將其推到一個變量dataxx但我不斷收到此錯誤:AngularJS http.jsonp回調沒有定義

Uncaught ReferenceError: myJsonMethod is not defined

documentation
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; 
      }); 
     } 
     } 
    }]); 
+0

http://stackoverflow.com/questions/12066002/parsing-jsonp-http-jsonp-response-in-angular-js – AlainIb

+0

你定義了函數myJsonMethod嗎?如果不是,你可以使用'JSON_CALLBACK' – maurycy

回答

1

報價約傳遞給jsonp方法url參數:

Relative or absolute URL specifying the destination of the request. The name of the callback should be the string JSON_CALLBACK.

所以:

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

另外,如果你想使用myJsonMethod確保你定義了這些功能將被稱爲:

function myJsonMethod(result) { 
    ... 
} 

在你的情況,你所用的標準.success回調在內部將定義一個名爲JSON_CALLBACK功能。

不幸的是,從我所看到的遠程端點完全忽略callback查詢字符串參數。下面的網址都返回相同的結果這是不對的,當然:

因此,我建議你與已實施此API和開發者交談的請他們不要硬編碼,如果可能的話,回調名稱,而是尊重查詢字符串參數。

如果出於某種原因,此API無法修復,那麼您唯一的機會就是定義一個函數myJsonMethod,正如我前面所示。