简体   繁体   English

我无法使用Angular $ http.get从php检索json数据

[英]I cannot retrieve json data from php with Angular $http.get

This my php code 这是我的PHP代码

    <?php


try {
    $dbcon=new PDO('mysql:host=localhost;dbname=angular;charset=utf8',"root","");

    $dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbcon->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
    $query="SELECT * FROM products ";
    $sql=$dbcon->prepare($query);
    $sql->execute();
    $result=$sql->fetchAll(PDO::FETCH_OBJ);

    $json_result=json_encode($result);

    echo $json_result;

}catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}


?>

and this my controller to angular 这是我的控制器

  function ProductListCtrl($http)
{

    $http.get('api/products.php').success(function (data) { alert(data); this.product = data; });

}

the alert message is [object Object,...] ,how can i retrieve the json data from php? 警报消息是[object Object,...],如何从php检索json数据?

$http.get work fine with JSON I recommend you to validate your json and test again I created a simple example for you with $http and ng-repeat $ http.get与JSON配合良好我建议您验证 json并再次测试我使用$ http和ng-repeat为您创建了一个简单示例

<!doctype html>
<html ng-app="test">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
    <script>
      var app = angular.module('test', []);
      app.controller('test', function($scope, $http) {
        $http.get('test.json').success(function(data){
          console.log(data);
          $scope.items = data;
        });
      });
    </script>
  </head>
  <body ng-controller="test">
    <div ng-repeat="item in items">{{item.name}}</div>
  </body>
</html>

and the json file is 和json文件是

[{
  "name":"name1"
},
{
  "name":"name2"
}]

and also a link to watch it live in Plunker http://plnkr.co/edit/MN6UPg1ba1OYNFNHKMdG?p=preview 以及在Plunker中观看直播的链接http://plnkr.co/edit/MN6UPg1ba1OYNFNHKMdG?p=preview

I solved the problem.The wrong is with this.product 我解决了这个问题。这个产品错了

(function ()
{
    "use strict";
   var app = angular.module('ProductList');
   app.controller('ProductListCtrl',['$scope','$http', ProductListCtrl]);

   function ProductListCtrl($scope, $http) {

       $http.get('api/products.php').success(function (data) { $scope.product = data; });




   }

}());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM