JSONP没有按预期在AngularJS中工作

时间:2014-07-30 17:50:12

标签: javascript angularjs jsonp

我从angular文档中获取的第一个注释$ scope.url工作正常,同样我试图调用另一个公共URL,它给我回复响应但总是进行错误回调。

这两个网址都属于公共领域,因此请随时尝试。

                $scope.method = 'JSONP';
             // URL 1: Working
             // $scope.url = 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero';

             // URL 2: Not working (Getting response with status 200OK but going to error callback)           
                $scope.url= 'http://apps.nlm.nih.gov/medlineplus/services/mpconnect_service.cfm?callback=JSON_CALLBACK&mainSearchCriteria.v.cs=2.16.840.1.113883.6.96&mainSearchCriteria.v.c=41381004&knowledgeResponseType=application/javascript';

                $scope.fetch = function() {
                    $scope.code = null;
                    $scope.response = null;

                    $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
                        success(function(data, status) {
                             console.log(data);
                             console.log(status);
                        }).
                        error(function(data, status) {
                            console.log(data);
                            console.log(status);
                        });
                };

enter image description here

1 个答案:

答案 0 :(得分:2)

出于某种原因正在从回调方法名http://apps.nlm.nih.gov/medlineplus/services/mpconnect_service.cfm?callback=angular.callbacks._0&mainSearchCriteria.v.cs=2.16.840.1.113883.6.96&mainSearchCriteria.v.c=41381004&knowledgeResponseType=application/javascript

中剥离

AngularJS 无法处理此响应,因为Angular想要调用angular.callbacks.0

一些开发背景

var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
    function() {
        if (callbacks[callbackId].data) {
            completeRequest(callback, 200, callbacks[callbackId].data);
        } else {
            completeRequest(callback, status || -2);
        }
        callbacks[callbackId] = angular.noop;
});

其中包含JSON_CALLBACK字符串的每个网址都将替换为angular.callbacks.{\D}

来源:AngularJS.js