Angularjs $http get method for JSONP data without

2020-05-06 00:17发布

问题:

I have problem by printing in the table, some JSON that is on the server. This is my JSON

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

My controller:

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);
    });

And this is my 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>

Have any idea where I'm wrong? tnx

回答1:

Try:

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);
})

For more information, see Not a Legal JSONP API


when I put {{myData}}, I have complet jsonp,

I am glad you were able to get the data with this answer. It shows that the server is not returning legal JSON. The server should be fixed to return either legal JSON or legal JSONP.

To make the server respond with a valid JSONP array, wrap the JSON in brackets () and prepend the callback:

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).")";

For more information, see Simple PHP and JSONP example



回答2:

I think there is something wrong with your json data.

i can see by changing you json data. you can have a look on it.

<!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>