【问题标题】:Exception handling with jsonp requests in angularjsangularjs中jsonp请求的异常处理
【发布时间】:2013-07-20 00:29:48
【问题描述】:

我有以下代码分别请求 jsonp 数据。 在代码中“doRequestA”工作正常并返回结果。我的问题是 如果发生任何错误,我需要捕获它们。我已经尝试在 “doRequestB”,但只收到警报错误(我省略了来自 doRequestB 的回调)。

这是小提琴http://jsfiddle.net/a4Rc2/417/

function jsonp_callback(data) {
    alert(data.found);
}

function jsonp_example($scope, $http) {
    $scope.doRequestA = function () {
        var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=jsonp_callback";
        $http.jsonp(url);
    };

    $scope.doRequestB = function () {
        var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts";
        $http.jsonp(url)
            .success(function (data) {
            alert(data.found);
        }).error(function (data, status, headers, config) {
            alert('error');
        });
    };
}

非常感谢任何建议,在此先感谢。

【问题讨论】:

    标签: angularjs jsonp


    【解决方案1】:

    您实际上在这两种情况下都错误地使用了$http.jsonp。您只是看不到第一种情况下的错误,因为您没有处理它。

    使用 Angular.js 的 $http.jsonp 方法,回调方法是自动处理的。您不应在结果字符串中使用自己的方法,而应将JSON_CALLBACK(完全按照所写)插入到您的字符串中。这样,您可以使用从 Angular 返回的承诺来处理响应。如果您观察网络活动(例如,在您选择的浏览器中使用 Firebug 或开发人员工具),您会看到 JSON_CALLBACK 被替换为 angular.callbacks._0* 之类的东西。

    在第二个示例中,您根本没有定义回调方法,因此结果将总是错误。 jsonp结果实际上是没有办法处理的,因为它只是返回了没有回调方法的JSON对象,结果只是被忽略了。

    这是一个工作结果:http://jsfiddle.net/tPLaN/1/

    代码:

    function jsonp_callback(data) {
    
        alert(data.found);
    }
    
    
    function jsonp_example($scope, $http) {
        $scope.doRequestA = function() {
    
            var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
    
            $http.jsonp(url).success(function(data) {
                jsonp_callback(data);
            });
        };   
    
    
        $scope.doRequestB = function() {
    
            var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
    
    
            $http.jsonp(url)               
             .success(function (data) {
    
                 alert(data.found);
    
            }).error(function (data, status, headers, config) {
    
                 alert('error');         
            });
        };       
    }
    

    我唯一改变的是

    1. 更正这两个 URL。
    2. 将回调处理程序移动到 promise 的 .success() 方法内的第一个方法上。

    信不信由你,JSON_CALLBACK 的需求 the documentation for $http.jsonp 中,但它有点隐藏。


    * 注意,请不要使用JSON_CALLBACK 的替代品来代替任何东西。这是 Angular 生成的私有方法,我只是展示它以帮助更了解正在发生的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-04
      • 2013-10-02
      • 2021-08-31
      相关资源
      最近更新 更多