dpnru86024 2014-11-21 18:29
浏览 50

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

This my php code

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

  • 写回答

2条回答 默认 最新

  • donglu4633 2014-11-21 19:55
    关注

    $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

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

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

    and also a link to watch it live in Plunker http://plnkr.co/edit/MN6UPg1ba1OYNFNHKMdG?p=preview

    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料