Angularjs $ http获取没有CALLBACK参数的JSONP数据的方法

时间:2017-07-11 16:08:34

标签: php angularjs json jsonp http-method

我在表中打印时遇到问题,服务器上有一些JSON。 这是我的JSON

process([
{
    "name": "A",
    "value": "41"
},
{
    "name": "B",
    "value": "71"
},
{
    "name": "C",
    "value": "20"
}],"2017.07.11 15:48:33");

我的控制器:

myApp.controller('liveTable', function ($scope, $http) {

$http.get('http://something.com/get.php?jsonp=2017')
    .then(function (response) {
        $scope.myData= response.data;
        console.log(response.data);
    });

这是我的HTML

 <div class="liveTable" ng-controller="liveTable">
             <table>
                <tr ng-repeat="item in myData.process">
                    <td>{{item.name}}</td>
                    <td>{{item.value}}</td>
                </tr>
            </table>

        </div>

知道我哪里错了吗? TNX

2 个答案:

答案 0 :(得分:0)

尝试:

app.service("dangerousAPI", function($q) {
  this.get = get;

  function get(funcName, url) {
    var dataDefer = $q.defer();

    window[funcName] = function(x) {
      dataDefer.resolve(x);
    }

    var tag = document.createElement("script");
    tag.src = url;

    document.getElementsByTagName("head")[0].appendChild(tag);

    return dataDefer.promise;
  }
})
dangerousAPI.get('process',url).then(function(data) {
     $scope.myData= data;
     console.log(data);
})

有关详细信息,请参阅Not a Legal JSONP API

  

当我放{{myData}}时,我有complet jsonp,

我很高兴您能够通过此答案获取数据。它表明服务器没有返回合法的JSON。应修复服务器以返回合法的JSON或合法的JSONP

要使服务器响应有效的JSONP数组,请将JSON括在括号()中并添加回调:

echo $_GET['callback']."([{'fullname' : 'Jeff Hansen'}])";
Using json_encode() will convert a native PHP array into JSON:

$array = array(
    'fullname' => 'Jeff Hansen',
    'address' => 'somewhere no.3'
);
echo $_GET['callback']."(".json_encode($array).")";

有关详细信息,请参阅Simple PHP and JSONP example

答案 1 :(得分:0)

我认为您的json数据存在问题。

我可以通过改变你的json数据来看到。你可以看看它。

&#13;
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<body>

<div ng-app="myapp">
 <div class="liveTable" ng-controller="myctrl">
             <table>
                <tr ng-repeat="item in process">
                    <td>{{item.name}}</td>
                    <td>{{item.value}}</td>
                </tr>
            </table>

        </div>
</div>
</div>
<script>
angular.module("myapp",[]).controller("myctrl", function($scope){
  $scope.process = ([
{
    "name": "A",
    "value": "41"
},
{
    "name": "B",
    "value": "71"
},
{
    "name": "C",
    "value": "20"
}]);
 

});
</script>

</body>
</html>
&#13;
&#13;
&#13;