Angular JSON 与 JSONP $promise

2024-05-06

如果我从我的controller.js进行这个JSON调用:

$scope.userInvestors = userInvestors.query({UserID:$scope.user.uid}, 
  function(userInvestors) {
    console.log("yep yer here");
}

有了这个$resource:

factory('userInvestors', function($resource){
  return $resource('http://wherevertheserveris/Rest/userInvestors.php', {}, {
    query: {method:'GET', params:{}, isArray:true}
  });
})

然后控制台按预期更新为: yep yer here

但是,如果我将请求更改为 JSONP 请求:

$scope.userInvestors = userInvestors.query({UserID:$scope.user.uid, 
  callback: 'JSON_CALLBACK'}, function(userInvestors) {
    console.log("but are you here?");
}

和资源:

factory('userInvestors', function($resource){
  return $resource('http://wherevertheserveris/Rest/userInvestors.php', {}, {
    query: {method:'JSONP', params:{}, isArray:true}

  });
})

即使我知道呼叫已完成并且已检索到数据,控制台也没有打印任何内容?

如何打印 JSONP 日志语句?

ANSWER:

感谢以下两个答案:我需要正确格式化 API 的返回响应。

在 NULL 的情况下,我通过 PHP 返回:print $callback."null";

我需要返回的只是函数包装器内的一个空数组,或者您认为合适的任何其他格式正确的 JSONP 响应。就我而言,是:print $callback."([])";


首先,您需要确定从后端返回的数据格式是什么。 JSONP 响应是一个 JSON 数据,其中包含一个函数调用。

我的 php API 实现:

<?php
    $callback = isset($_GET['callback'])?$_GET['callback']:'JSON_CALLBACK';

    $array = array("name"=>"test","email"=>"[email protected] /cdn-cgi/l/email-protection");

    echo $callback."(".json_encode($array).")";
?>

因为包装的函数调用名称是由参数“callback”确定的,所以当您使用 ngResource 模块时,请记住为回调参数和自定义方法属性“callback”分配正确的名称。

角度实现:

angular.module("app",['ngResource'])
.controller("myCtrl",function($scope,userInvertors){
    $scope.jsonpTest = function(){
        $scope.result = userInvertors.query(function(response){
            console.log(response);
        });
    }
})
.factory("userInvertors",function($resource){
    return $resource('http://your.domain.com/API/getUser/123',{},{
        query:{
            method:'JSONP',
            params:{callback:"JSON_CALLBACK"},
            callback:"JSON_CALLBACK"
        }
    });
});

HTML

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ngResource</title>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular-resource.js"></script>
        <script src="js/ngResource.js"></script>
</head>
<body ng-app="app">
    <div ng-controller="myCtrl">
        <input type="button" ng-click="jsonpTest()" value="JSONP"/>
    </div>
</body>
</html>

截屏:

API:

Get response: enter image description here

希望这对您有帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular JSON 与 JSONP $promise 的相关文章

随机推荐